Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xpath to get element value

Tags:

xml

xpath

I am trying to use xpath to get the value of Odometer out of my xml file:

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

I have tried about anything but I can not get a working xpath:

CWEAI/cwReturnTruckCanbusHistory/Odometer

CWEAI/cwReturnTruckCanbusHistory/Odometer/text

CWEAI[@xmlns="http://www.carrierweb.com/Schema/CWEAI_schema_1.0/cwReturnTruckCanbusHistory"]/cwReturnTruckCanbusHistory/Odometer
like image 291
Tom Reinders Avatar asked Jan 04 '23 01:01

Tom Reinders


1 Answers

text is Xpath function, so use it in the proper way

/CWEAI/cwReturnTruckCanbusHistory/Odometer/text()

It results in Text='1374031'

Working in 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

like image 160
splash58 Avatar answered Jan 12 '23 12:01

splash58