简体   繁体   中英

Using XPath to search with, and retrieve attribute in XML

I'm trying to use XPath to retrieve an attribute value in an XML file containing a lot of data. I want to search the XML file for a particular attribute, and return a corresponding attribute.

My code at the moment gives an Expression Error which I guess means I've gotten the expression wrong.

private String getPrivateID(String platformNo)
{

    String platformTag = null;

    try
    {
        InputStream is = getResources().openRawResource(R.raw.platform);
        InputSource inputSrc = new InputSource(is);

        XPath xpath = XPathFactory.newInstance().newXPath();

        String expression = String.format("//Platform[@PlatformNo=%s]/@PlatformTag", 
            platformNo);
        NodeList nodes = (NodeList) xpath.evaluate(expression, 
            inputSrc, XPathConstants.NODESET);

        platformTag = xpath.evaluate(expression, nodes);

        return platformTag;

    }
    catch (Exception e)
    {
        return null;
    }
}

My XML is like this:

<JPPlatforms>
  <Platform PlatformTag="2980" PlatformNo="47280" Name="AGHS" 
       BearingToRoad="2.6606268e+002" RoadName="Avonside Dr">
    <Position Lat="-4.352447905000000e+001" Long="1.726611665000000e+002"/>
  </Platform>
  <Platform PlatformTag="1219" PlatformNo="28142" Name="Addington Village" 
       BearingToRoad="3.2193924e+002" RoadName="Lincoln Rd">
    <Position Lat="-4.354269524000000e+001" Long="1.726134222000000e+002"/>
  </Platform>
  <Platform PlatformTag="1220" PlatformNo="44108" Name="Addington Village" 
       BearingToRoad="1.4198888e+002" RoadName="Lincoln Rd">
    <Position Lat="-4.354386705000000e+001" Long="1.726111654000000e+002"/>
  </Platform>
  <Platform PlatformTag="2940" PlatformNo="45477" Name="Aidanfield Dr near Bibiana St" 
       BearingToRoad="2.1811232e+002" RoadName="Aidanfield Dr">
    <Position Lat="-4.356581921000000e+001" Long="1.725743414000000e+002"/>
  </Platform>
  <Platform PlatformTag="2941" PlatformNo="47192" Name="Aidanfield Dr near Bibiana St" 
       BearingToRoad="3.8112324e+001" RoadName="Aidanfield Dr">
    <Position Lat="-4.356595693000000e+001" Long="1.725742336000000e+002"/>
  </Platform>
<JPPlatforms>

Where have I gone wrong? Thanks in advance!

The xpath

//Platform[@PlatformNo=%s]/@PlatformTag

extracts an attribute, whereas you are attempting to evaluate a NODESET . Since you only need to return a single scalar value, try:

String platformTag = (String) xpath.evaluate(expression, inputSrc, XPathConstants.STRING);

You may also consider escaping the number with quotes:

//Platform[@PlatformNo='%s']/@PlatformTag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM