我试图解析下列字符串以形成一个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