简体   繁体   English

使用XPath进行XML搜索和检索属性

[英]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. 我正在尝试使用XPath在包含大量数据的XML文件中检索属性值。 I want to search the XML file for a particular attribute, and return a corresponding attribute. 我想在XML文件中搜索特定的属性,然后返回相应的属性。

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: 我的XML是这样的:

<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 xpath

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

extracts an attribute, whereas you are attempting to evaluate a NODESET . 提取属性,而您尝试评估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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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