我尝试使用XPath检索包含大量数据的XML文件中的属性值。我想在XML文件中搜索特定属性,并返回相应的属性。
我的代码目前给出了表达式错误,我猜这意味着我的表达错误。
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;
}
}
我的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>
我哪里出错了?提前谢谢!
答案 0 :(得分:1)
xpath
//Platform[@PlatformNo=%s]/@PlatformTag
提取属性,而您尝试评估NODESET
。由于您只需要返回单个标量值,请尝试:
String platformTag = (String) xpath.evaluate(expression, inputSrc, XPathConstants.STRING);
您也可以考虑使用引号转义该数字:
//Platform[@PlatformNo='%s']/@PlatformTag