user3050478
user3050478

Reputation: 273

I need to read a XML attribute of a tag inside another tag

I was trying to solve it alone but has been passed weeks and I can't solve that...

I have a XML like this one:

<?xml version="1.0" encoding="UTF-8"?>

<clothes>

<clothe premium="no" id="1">
    <list gender="0" style="11" name="Jacket"/>
    <list gender="1" style="12" name="Jacket"/>
</clothe>

<clothe premium="yes" id="2">
    <list gender="0" style="13" name="Pants"/>
    <list gender="1" style="14" name="Pants"/>
</clothe>

</clothes>

I want to read on the "clothe" the attributes: 'premium' and 'id' and on the "list" below it the attributes: 'gender', 'style' and 'name'.

Obs: the best I've ever done was make the php read the first or the last "list" attributes and I need to read all the tags inside the "clothe".

Gender 0 = Male Gender 1 = Female

Here is an example that I've used and that I need help with:

public function getClothes()
{
    $clothes = array();

    foreach( $this->element->getElementsByTagName('list') as $list)
    {
        $clothes[] = $list->getAttribute('gender');
        $clothes[] = $list->getAttribute('style');
        $clothes[] = $list->getAttribute('name');
    }

    return $clothes;
}

Upvotes: 0

Views: 149

Answers (1)

Marc B
Marc B

Reputation: 360672

DOM nodes are members of a tree, and are fully aware of their parents/descendants. So... search for the clothe elements:

$clothes = $this->element->getElementsByTagName('clothe');
foreach($clothes as $clothe) {
    $premium = $clothe->getAttribute('premium');

    $lists = $clothe->getElementsByTagName('list'); // get all `<list>` under the current node
    foreach($lists as $list ) {
         $gender = $list->getAttribute('gender');
         ...
    }
}

and once you've got a <clothe> element, search for all <list> below it.

Upvotes: 1

Related Questions