閱讀658 返回首頁    go 阿裏雲 go 技術社區[雲棲]


java操作XML中的占位符

有時XML的某些內容是待定的,對於這些內容可以在XML文件中使用占位符

<people>
 <person >
  <name>$name</name>
  <age>$age</age>
 </person>
</people>

 

讀取該文件的時候可以為其中的占位符設置值

/**
 * IO操作工具類
 * 
 * @author 徐越
 * 
 */
public class IOUtils
{
	/**
	 * 讀取輸入流為byte[]數組
	 */
	public static byte[] read(InputStream instream) throws IOException
	{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = instream.read(buffer)) != -1)
		{
			bos.write(buffer, 0, len);
		}
		return bos.toByteArray();
	}
}

InputStream instream = this.getClass().getClassLoader().getResourceAsStream("person.xml");
String oldXML = new String(IOUtils.read(instream), "UTF-8");
String newXML = oldXML.replaceAll("\\$name", "徐越").replaceAll("\\$age","22");

要說明的是replaceAll第一個參數是正則表達式,正則表達式中$需要用\轉義。

Java中對\又需要用\進行轉義,所以寫成\\$name 。

 

最後更新:2017-04-04 02:25:10

  上一篇:go php之遞歸調用,遞歸創建目錄
  下一篇:go java操作XML中的占位符