简体   繁体   中英

Filtering XML attributes with xpath in PHP

This is my XML file:

<?xml version="1.0" encoding="utf-8"?>
<sets>
  <set name="default">
    <phpClass name="ArrayIterator" />
  </set>
  <set name="production" basedOn="default">
    <phpVersion>
      <min>5.3.0</min>
    </phpVersion>
  </set>
</sets>

I have to get all items(set) and assign for example phpClass from default (or another) from XML, where sets are connected with basedOn . There is much more main sets (set with diffarent name) and a lot of sets with basedOn. This must be dynamically on more websites, I do not know all names and basedOn-s, so it will be dynamically script.

This is PHP what I have now (for testing):

$this->xml = simplexml_load_file($file);
print_r($this->xml->xpath("//sets/set[contains(name, 'default')]"));

But I get this: Array ( )

Any ideas? Maybe I am not much clear, so ask when you don't understand something.

you are trying to select a set that has a name element that contains 'default' you need to use @name to select the attribute instead:

$this->xml = simplexml_load_file($file);
print_r($this->xml->xpath("//sets/set[contains(@name, 'default')]"));

As a sidenote, there seems to be no need to use contains which is ususally used when you have something like a html class attribute where you have multiple classes, here you can just use set[@name='default'] instead.

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