XML解析的Java(Android版)(XML parsing Java (Android))

2019-10-30 14:38发布

我从Web服务的XML请求。 它看起来像这样。 所以,我怎样才能得到订单ID值? 我从来没有在Java XML工作。

<order1s uri="http://mywebsite/rest/create_order">
<order1 uri="http://mywebsite/rest/create_order/401/"> 
<customer uri="http://mywebsite/rest/create_order/401/customer/">
<name/>
<passengerId>123</passengerId>
<phone/>
<rating>0.0</rating>
<restToken>
985y3289y5v43535v032m0v3v0b0jcrmjsa9w20m02umc3
</restToken>
<surname/>
</customer>
<offerCollection uri="http://mywebsite/rest/create_order/401/offerCollection/"/>
<orderId>401</orderId>
<orderWaypointsCollection uri="http://mywebsite/rest/create_order/401/orderWaypointsCollection/">
<orderWaypoints uri="http://mywebsite/rest/create_order/401/orderWaypointsCollection/null/">
<isStartPoint>true</isStartPoint>
<latitude>50.505463</latitude>
<longitude>30.44121</longitude>
<norder uri="http://mywebsite/rest/create_order/401/orderWaypointsCollection/null/norder/"/>
</orderWaypoints>
<orderWaypoints uri="http://mywebsite/rest/create_order/401/orderWaypointsCollection/null/">
<isStartPoint>false</isStartPoint>
<latitude>50.4501</latitude>
<longitude>30.5234</longitude>
<norder uri="http://mywebsite/rest/create_order/401/orderWaypointsCollection/null/norder/"/>
</orderWaypoints>
</orderWaypointsCollection>
<status>1</status>
<toDate>19/05/2011 17:49:12</toDate>
<toNow>true</toNow>
</order1>
</order1s>

Answer 1:

我建议使用XPath的 :

这将是这样的:

XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "orderId";
InputSource inputSource = new InputSource(xmlInputStreamOrReaderOrSomethingElse). 
String id = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);

更新:

表达式必须是"//orderId" : 例如



Answer 2:

如果你想使用内置于平台的工具来分析它,你可以使用SAX DefaultHandler 。 现在有很多答案在这里指向的教程。

如果你只需要在orderId其他值的价值,没有的话,我只想使用像正则表达式提示:

<orderId>(\d+)<\/orderId>  


文章来源: XML parsing Java (Android)