tags:

views:

156

answers:

2

I have a XML org.w3c.dom.Document object.

It looks sorta like this:

<A>
  <B>
     <C/>
     <D/>
     <E/>
     <F/>
   </B>
   <G>
     <H/>
     <H/>
     <J/>
   </G>
 </A>

How can I convert the Document object so that it strips off the root node and returns another Document object subset (selected by name) that looks like this:

<G>
   <H/>
   <H/>
   <J/>
</G>

I am hoping for something like this:

...
Document doc = db.parse(file);
Document subdoc = doc.getDocumentSubsetByName("G"); //imaginary method name
NodeList nodeList = subdoc.getElementsByTagName("H");

But I am having trouble finding such a thing.


The answer turns out to be something like this:

...
Document doc = db.parse();
doc.getDocumentElement.normalize();
NodeList a = doc.getElementsByTagName("A");
Element AsubNode = null;
if (a.item(0) != null) {
   AsubNode = (Element) a.item(0);
   nodeList = AsubNode.getElementsByTagName("G");
...
A: 

You can simply use getElementsByTagName("G") to get the G elements, then pick one of them and call getElementsByTagName("H") on that.

Greg Hewgill
that first method gets me a NodeList object but I want to "end up" with a NodeList. therefore, I need to subset the document "before" I convert to a NodeList. that is the dilemma.
djangofan
I don't quite understand the difficulty with that. From a NodeList, you can get a specific Node, which you can then cast to an Element (if necessary, depending on your language) and then call getElementsByTagName on the Element.
Greg Hewgill
Oh I see you're using Java. So yes, you'll have to cast.
Greg Hewgill
with your help I got it. thanks.
djangofan
A: 

Of course, you could always use XPath to do the same thing:

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NodeList;

final XPath xpath = XPathFactory.newInstance().newXPath();
final NodeList list = (NodeList) xpath.evaluate("/A/G/H", 
    doc.getDocumentElement(), XPathConstants.NODESET);

This begins to pay off when the path to your elements begins to become more complex (requiring attribute predicates, etc..)

toolkit
thank you very much!
djangofan