开发者

How to get a node from xml not knowing its level in Java

开发者 https://www.devze.com 2023-03-22 04:40 出处:网络
We have tree structure like this: 开发者_StackOverflow中文版<Tree> <child1> <child2>

We have tree structure like this:

开发者_StackOverflow中文版<Tree>
   <child1>
         <child2>
         <child2>
   </child1>
</Tree>

Here the child2 can be at any level. Is there any way we can access child2 without knowing the hierarchy?

Thanks for all answer..is there any way in Castor?as we are using Castor for marshalling and unmarshilling

Here is a similar type of question: How to get a node from xml not knowing its level in flex?


Using XPath, you could do it something like this:

XPath xpath = XPathFactory.newInstance().newXPath();
NodeList child2Nodes= (NodeList) xpath.evaluate("//child2", doc, 
    XPathConstants.NODESET);

Where doc is your org.w3c.dom.Document class.


Use XPath to get the nodes.
//child2 - to get the list of all "child2" elements


If you can use SAX parser than it is easy here your ContentHandler

public class CH extends DefaultHandler
{
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
    {
      if (qName.equals("child2"))
      {
          // here you go do what you need here with the attributes 
      }
    }
}

pass it to parser and you are done

like

import org.xml.sax.*;

public class TestParse {

  public static void main(String[] args) {
    try {
      XMLReader parser = 
          org.xml.sax.helpers.XMLReaderFactory.createXMLReader();

      // Create a new instance and register it with the parser
      ContentHandler contentHandler = new CH();
      parser.setContentHandler(contentHandler);

      parser.parse("foo.xml"); // see javadoc you can give it a string or stream 
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消