reading xml: can xpath read 2 fields?
I'm using SimpleXMLElement and xpath to try and read the <subcategory><name>
from the xml at the very bottom. This code works.. but the stuff inside the while
loop looks a little messy, and now I also want to get the <subcategory><count>
and somehow pair it with its appropriate <subcategory><name>
.
$names = $xml->xpath('/theroot/category/subcategories/subcategory/name/');
while(list( , $node) = each($names)) {
echo $node;
}
My question: Is it possible to get this pairing while still using xpath since it looks like it can make the job easier?
<theroot>
<category>
<name>Category 1</name>
<subcategories>
<subcategory>
<name>Subcategory 1.1</name>
<count>18</count>
</subcategory>
<subcategory>
<name>Subcategory 1.2</name>
<count>29</count>
</subcategory>
</subcategories>
&开发者_StackOverflow社区lt;/category>
<category>
<name>Category 2</name>
<subcategories>
<subcategory>
<name>Subcategory 2.1</name>
<count>18</count>
</subcategory>
<subcategory>
<name>Subcategory 2.2</name>
<count>29</count>
</subcategory>
</subcategories>
</category>
</theroot>
If you are using SimpleXML, and you know the exact layout, it might be easier to do this:
$subcategories = $xml->xpath('/theroot/category/subcategories/subcategory');
foreach($subcategories as $subcategory){
echo $subcategory->name.'='.$subcategory->count;
}
With XPath, you could ofcourse select all subnodes of subcategory
, but pairing them back up could be more trouble then just foregoing xpath for the last node.
精彩评论