0

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??

Sanchit
  • 428
  • 1
  • 5
  • 24
nath
  • 2,848
  • 12
  • 45
  • 75
  • possible duplicate of [Create XML document using nodeList](http://stackoverflow.com/questions/5786936/create-xml-document-using-nodelist) –  Apr 26 '11 at 17:38

2 Answers2

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
0

refer Create XML document using nodeList

Community
  • 1
  • 1
nath
  • 2,848
  • 12
  • 45
  • 75