简体   繁体   中英

Using simplexml to get a node (and its children) by attribute

Using simplexml, is it possible to get the children of a node based on the parent's attributes. For example, I want to get a list of the variants in myItem1 (output would be small, large)

Here is some psuedo code of what I'm after:

foreach($xml->xpath('//family[@name="myItem1"]')->variants->children() as $child) {
    $child->getName()
}

(Of course this doesn't work, but hopefully it describes what I'm trying to do.)

Sample XML:

<library>
 <family name="myItem1">
   <variants>
    <small>
     ...
    </small>
    <large>
     ...
    </large>    
   </variants>
 </family>
 <family name="myItem2">
   <variants>
    <small>
     ...
    </small>
    <medium>
     ...
    </medium>   
   </variants>
 </family>
</library>

Thank you.

If I understand correctly, you want to get the names of all the children of a given node. There are various way to do it, one of them is to iterate over all the children, like this:

foreach ($xml->xpath('//family[@name="myItem1"]') as $family)
{
    $variants = array();
    foreach ($family->variants->children() as $name => $node)
    {
        $variants[] = $name;
    }

    // in case there are duplicates you can do
    $variants = array_unique($variants);

    var_dump($variants);
}

尝试以下XPath表达式:

//family[@name="myItem1"]/variants/*

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