0
votes

How would you print an Ability-elements Default-attribute value on the following XML if you only have the element's name and the ability id?

For example if I have the name 'steve' and id 1003 how would I then select and print that ability default value which is 'false'.

<Item Id="1">
<Name>Batman</Name>
<Ability Id="3001" Default="true">Super Strength</Ability>
<Ability Id="3002" Default="false">Master martial artist</Ability>
<Ability Id="3003" Default="false">Access to high tech</Ability>
</Item>

<Item Id="2">
<Name>Superman</Name>
<Ability Id="3004" Default="true">Flight</Ability>
<Ability Id="3005" Default="false">Super Strength</Ability>
<Ability Id="3006" Default="false">Super Speed</Ability>
<Ability Id="3007" Default="true">Stamina</Ability>
<Ability Id="3008" Default="false">Invulnerability</Ability>
</Item>

<Item Id="3">
<Name>Spiderman</Name>
<ScopeNotes/> <HistoryNotes/>
<Ability Id="219" Default="false">Super Reflex & Agility</Ability>
<Ability Id="567" Default="true">Spider Sense</Ability>
</Item>

<Item Id="4">
<Name>Steve</Name>
<Ability Id="1007" Default="false">Cake eating</Ability>
<Ability Id="1001" Default="true">Swearing</Ability>
<Ability Id="1002" Default="false">Watching movies</Ability>
<Ability Id="1003" Default="false">Steve</Ability>
</Item>

The problem is that each element has a different number of ability nodes and that the name 'Steve' occurs both in the name and ability node.

Ive read through the php dom documentation and have used it before to loop through items and obtain names (e.g.new DOMDocument, loading a file, getElementsByTagName) but I am having difficulty understanding how it works when you attempt do do something like I have explained above.

1
Maybe look into XPath, it is very powerful for querying information in an XML documentBob Fincheimer

1 Answers

1
votes

As suggested By Bob Fincheimer, XPath should be a good approach. The following path should give you the result

//Item[Name="Steve"]/child::Ability[@Id="1003"]/@Default

Explanation of the path:

  1. //
    select nodes everywhere in the document(I don't know the complete xml)
  2. Item
    select <Item>-nodes
  3. [Name="Steve"]
    select nodes that have a child-element <Name> with the nodeValue "Steve"
  4. child::Ability
    select child-nodes <Ability>
  5. [@Id="1003"]
    select Nodes with a Id-attribute set to 1003
  6. @Default
    select the Default-attribute

For the given XML it will return a DOMNodeList with 1 attribute-node (@Default="false")

How to use it? http://www.php.net/manual/de/domxpath.query.php

Demo: http://codepad.org/qtgWXFtm