获取元素值的Xpath

时间:2017-05-10 13:27:13

标签: xml xpath

我正在尝试使用xpath从我的xml文件中获取Odometer的值:

<?xml version="1.0"  encoding="UTF-8"?>
<CWEAI xmlns="http://www.carrierweb.com/Schema/CWEAI_schema_1.0/cwReturnTruckCanbusHistory">

  <cwReturnTruckCanbusHistory>
    <ID>549094411</ID>
    <CWVehicleID>109755</CWVehicleID>
    <Odometer>1374031</Odometer>
    <Fuel>452800</Fuel>
    <FuelLevel>1000</FuelLevel>

  </cwReturnTruckCanbusHistory>
</CWEAI>

我尝试过任何事情但我无法获得正常的xpath:

CWEAI/cwReturnTruckCanbusHistory/Odometer

CWEAI/cwReturnTruckCanbusHistory/Odometer/text

CWEAI[@xmlns="http://www.carrierweb.com/Schema/CWEAI_schema_1.0/cwReturnTruckCanbusHistory"]/cwReturnTruckCanbusHistory/Odometer

1 个答案:

答案 0 :(得分:2)

text是Xpath函数,因此请以正确的方式使用它

/CWEAI/cwReturnTruckCanbusHistory/Odometer/text()

结果为Text='1374031'

在php中工作:

$xml = simplexml_load_string($str);
$ns = $xml->getNamespaces(true); 
$xml->registerXPathNamespace('c', current($ns));

$target = $xml->xpath('//c:CWEAI//c:cwReturnTruckCanbusHistory/c:Odometer/text()');
echo $target[0];

<强> demo on eval.in