DocumentBuilder使用換行符和xml字符串爲不帶換行符的xml字符串構建不同的DOM對象。下面是我測試的代碼:
StringBuilder sb = new StringBuilder();
sb.append("<root>").append(newlineChar).append("<A>").append("</A>").append(newlineChar).append("<B>tagB").append("</B>").append("</root>");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputStream xmlInput = new ByteArrayInputStream(sb.toString().getBytes());
Element documentRoot = builder.parse(xmlInput).getDocumentElement();
NodeList nodes = documentRoot.getChildNodes();
System.out.println("How many children does the root have? => "nodes.getLength());
for(int index = 0; index < nodes.getLength(); index++){
System.out.println(nodes.item(index).getLocalName());
}
輸出:
How many children does the root have? => 4
null
A
null
B
但是,如果新newlineChar
從StringBuilder的刪除, 的ouptput是:
How many children does the root have? => 2
A
B
這演示由DocumentBuilder生成的DOM對象是不同的。
感謝的信息,在末尾位,好知道 – Candyfloss 2010-08-04 10:09:57
這是不正確的。我測試過了。使用換行符和無換行符的xml字符串構建DOM對象是不同的! – sarahTheButterFly 2010-09-23 05:25:07