我試圖解析下列字符串以形成一個xml文檔,然後嘗試提取所有子節點並添加到已經提供給我的不同文檔對象。混合文本和元素節點時,XML子節點迭代的問題
<dhruba><test>this</test>that<test2>wang chu</test2> something.... </dhruba>
<dhruba>this is text node <test>this</test>that<test2>wang chu</test2> anything..</dhruba>
,而我想讀的子節點,則返回null孩子TEXT_NODE爲1弦和空值ELEMENT_NODE的第二根弦,這是錯誤的,是API的問題?
我使用下面的代碼...它編譯,我用java 6
Node n = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dom = db.newDocument();
Element rootEle = dom.createElement("resources");
// adding the root element to the document
dom.appendChild(rootEle);
Element element = dom.createElement("string");
element.setAttribute("name", "some_name");
try {
n = db.parse(new InputSource(new StringReader("<dhruba><test>this</test>that<test2>node value</test2> some text</dhruba>"))).getDocumentElement();
n = dom.importNode(n, true);
NodeList nodeList = n.getChildNodes();
int length = nodeList.getLength();
System.out.println("Total no of childs : "+length);
for(int count = 0 ; count < length ; count++){
Node node = nodeList.item(count);
if(node != null){
element.appendChild(node);
}
}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rootEle.appendChild(element);
INPUT ::作爲字符串
<dhruba><string name="some_name">
that
<test>this</test>
<test2>node value</test2>
some text
</string>
</dhruba>
預期產出::作爲文檔
<string>
<string name="some_name">
<test>this</test>
<test2>node value</test2>
</string>
</string>
如果我試圖解析
<test>this</test>that<test2>wang chu</test2> something....
然後輸出當屬 「thiswang楚」
Why is this happening? what needs to be done if I want to add following node under another document element, i.e. <string>.
<test>this</test>
that
<test2>node value</test2>
some text
[notice that it does not have <dhruba>] inside parent node of another
document.
希望我是清楚的。以上代碼在Java編譯6
非常感謝Grzegorz,cloneNode(true)工作正常。你爲我節省了更多的時間。 – Dhrubo
@Dhrubo:不客氣:)您可能會將我的答案標記爲已接受(http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) –
如何接受?我在這個網站是新的..請指導。我已經使用上面的鏈接,但它是一個meta.stackoverflow網站,我很困惑點擊什麼.. :( – Dhrubo