Search code examples
javaxerces

Loading java object when parsing xml using SAX xerces


If my xml looks like:

<root version="1.1">
  <node number="1">
    <url>http://....</url>
  </node>
  <url>http://...</url>
</root>

Now in my endElement event I look if the xml element starts with 'url', but how do I know when the url element is the url element inside the node element and when it is not?

public void endElement(String uri, String localName, String qName, Attributes attributes) {
  if(qName.equals("url")) {
    someObject.setUrl(characters);
  }
}

Solution

  • one way is to keep track of elements "seen" either by maintaining a stack of element names or using a flag that indicates you're inside of a subtree.

    First way: in startElement push the element name on a stack, then in endElement pop the name off the stack. When you see "url" in endElement, check if "node" is on the stack.

    Another way: in startElement set nodeElementSeen = true, then in endElement set nodeElementSeen = false. When you see "url" in endElement, check if nodeElementSeen = true.