I'm reading xml document using XPath and I need to create a Document object using the result of XPath evaluation. Can some one tell me how to do this??
Asked
Active
Viewed 6,142 times
2 Answers
3
Assuming that your xpath returns a single node, you can do something like:
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
doc.appendChild(doc.importNode(xpathResult, true));
If it returns a node set, you will have to create a root element yourself.
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
doc.appendChild(doc.createElement("root"));
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
doc.getDocumentElement().appendChild(doc.importNode(node, true));
}

nabeelmukhtar
- 1,371
- 15
- 24
-
Actually it returns Node set. So this is not going to work for me. Is there a way to append Node List to the document. – nath Apr 26 '11 at 06:11