简体   繁体   中英

Get XML-node by attribute name

I have the following XML-structure:

   <Folder>
      <Placemark>
        <ExtendedData>
          <Data name="Id">
            <value>152285415</value>
          </Data>
          <Data name="Name">
            <value>Tester</value>
          </Data>
        </ExtendedData>
      </Placemark>
    </Folder>

and I need to directly access the of the -Object with the attribute "name" = "Id".

So I tried this:

$xml->Document->Folder->Placemark->ExtendedData->xpath('data[@name="Id"]')

but that gives and empty array.

What I need in the end is "152285415"

Any help appreciated.

This seems to do the job:

<?php

$xml = '<Folder>
      <Placemark>
        <ExtendedData>
          <Data name="Id">
            <value>152285415</value>
          </Data>
          <Data name="Name">
            <value>Tester</value>
          </Data>
        </ExtendedData>
      </Placemark>
    </Folder>';

$xml = simplexml_load_string($xml);

foreach($xml->Placemark->ExtendedData->Data as $item) {

    if($item->attributes()['name'] == 'Id') {
        echo $item->value;
    }

}

You can use XPath to access what you want directly:

<?php
$xml = '<Folder>
      <Placemark>
        <ExtendedData>
          <Data name="Id">
            <value>152285415</value>
          </Data>
          <Data name="Name">
            <value>Tester</value>
          </Data>
        </ExtendedData>
      </Placemark>
    </Folder>';

$xml = new SimpleXMLElement($xml);
$result = $xml->xpath('/Folder/Placemark/ExtendedData/Data[@name="Id"]');
echo "Value: ".$result[0]->value; // Value: 152285415

Demo

To not worry about the overall hierarchy of the document (although this is abused quite a bit) is to use // as the first part of the XPath. So the query can be written as in...

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$xmlDoc = <<<XML
<Folder>
  <Placemark>
    <ExtendedData>
      <Data name="Id">
        <value>152285415</value>
      </Data>
      <Data name="Name">
        <value>Tester</value>
      </Data>
    </ExtendedData>
  </Placemark>
</Folder>
XML;

$xml = new SimpleXMLElement($xmlDoc);
$value = $xml->xpath('//Data[@name="Id"]/value')[0];
echo "Value=".$value.PHP_EOL;

Although note that $value is still a SimpleXMLElement Object, so if you need it as a string, you should use (string)$value . In the example, echo will automatically do the conversion for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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