Search code examples
javaxmlxpathsaxxmldog

How to retrieve value from xml file using XMLDog


I am learning how to use SAX with xpath from this tutorial. and I wrote the below code, but it returns null instead of displaying '30'

please let me know how to solve it, and is there any other library for using SAX with Xpath?

Code:

DefaultNamespaceContext nsContext = new DefaultNamespaceContext(); // an implementation of javax.xml.namespace.NamespaceContext
    nsContext.declarePrefix("xsd", Namespaces.URI_XSD);

    XMLDog dog = new XMLDog(nsContext);
    XPathResults results = dog.sniff(new InputSource("c:\\brem.xml"));

    Expression xpath1 = dog.addXPath("//node[@lat='53.0334062'] [@lon='8.8461545']/following-sibling::tag[1]/@v");
    Log.d("", "", ""+results.getResult(xpath1));

xml:

<?xml version='1.0' encoding='utf-8' ?>
<osm>
<node id="25779111" lat="53.0334062" lon="8.8461545"/>
<node id="25779112" lat="53.0338904" lon="8.846314"/>
<node id="25779119" lat="53.0337395" lon="8.8489255"/>
<tag k="maxspeed" v="30"/>
<tag k="maxspeed:zone" v="yes"/>
<node id="25779114" lat="53.334062" lon="8.841545"/>
<node id="25779117" lat="53.038904" lon="8.84614"/>
<node id="25779110" lat="53.033795" lon="8.489255"/>
<tag k="maxspeed" v="32"/>
<tag k="maxspeed:zone" v="no"/>
</osm>

Solution

  • You should add xpaths before sniffing:

    DefaultNamespaceContext nsContext = new DefaultNamespaceContext();
    
    XMLDog dog = new XMLDog(nsContext);
    Expression xpath1 = dog.addXPath("//node[@lat='53.0334062'] [@lon='8.8461545']/following-sibling::tag[1]/@v");
    XPathResults results = dog.sniff(new InputSource(""c:\\brem.xml"));
    List<NodeItem> list = (List<NodeItem>)results.getResult(xpath1);
    System.out.println(list.isEmpty() ? null : list.get(0).value);
    

    this prints:

    30