tags:

views:

39

answers:

2

Let's say we have an org.w3c.dom.Document representing the following XML:

<Fruits>
  <Apples>
    <Red/>
    <Green/>
  </Apples>
</Fruits>

If we know that the document always will contain a <Fruits> root with only one child (in this case <Apples>, but the name of the child is generally unknown), how can we make that child the root of a new org.w3c.dom.Document? In other words, this new document should represent the following XML:

<Apples>
  <Red/>
  <Green/>
</Apples>

My problem is that when I try to extract the child, I can't make it forget its parent (it still remembers its position in the original document).

+1  A: 

Something like this:

    Node apples = doc.getFirstChild().getFirstChild(); 
            //or whatever is your way to find the node to copy
    Document newDocument = builder.newDocument();
    Node applesCopy = newDocument.importNode(apples, true);
    newDocument.appendChild(applesCopy);

Basically, you get a node from the old document, import it to the new document and append it to the top.

unbeli
Thank you! I first had some problems with getFirstChild() returning a whitespace node, but after removing the whitespace from the XML it now works well.
hakos
A: 

A viable alternative for the example you give is to work on unparsed Strings and use a regex to pull out the part you want.

That doesn't scale well to more complex processing. But it's probably the easiest and most efficient solution for simple cases.

Daniel Winterstein