Aada
Aada

Reputation: 1640

in JAVA how to jump to particular node in XML?

I have xml having data something like this

<A Name="">
</A>
<A Name="">
</A>
.....

How can i jump to some particular node and read it - like 3rd tag- A by using SAX parser

Upvotes: 1

Views: 1221

Answers (4)

jboi
jboi

Reputation: 11892

You cannot jump to (skip all elements before) a certain element using SAX. It reads sequentially all elements and returns them to your ContentHandler. All you can do, is skip the parsing, after you found the relevant element by throwing an exception from within the ContentHandler.

If you're looking for a kind of random access to the XML elements, then you should definitively consider DOM as pointed out by @Guillaume.

Upvotes: 1

Guillaume
Guillaume

Reputation: 5555

If you want to jump to a sub-node you must use the DOM API and not SAX.

  // load the document
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder(); 
  Document doc = db.parse(new File(filename));

  // prepare result list
  ArrayList<Element> res = new ArrayList<Element>();

  // prepare to use xpath
  XPath xpath = XPathFactory.newInstance().newXPath();
  // read 3rd A element
  NodeList list = (NodeList) xpath.compile("/A[3]")
      .evaluate(doc, XPathConstants.NODESET);

  // copy the DOM element in the result list
  for (int i = 0; i < list.getLength(); i++) {
    res.add((Element) list.item(i));
  }

Please note that contrary to SAX it will read the whole document before allowing you to access it.

Upvotes: 2

keaplogik
keaplogik

Reputation: 2409

Your best off using the Java StAX API. The Oracle Java Tutorial Site has a great read on how to work with it. It's very clean and simple for doing basic read/parse from XML.

Upvotes: -1

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can "jump" to a particular XML tag, but reading the tags in sequence. There is no reliable way to skip tags without reading.

Upvotes: 0

Related Questions