I'm having an issue with the moveToAttribute
method from PHP's XMLReader
class.
I don't want to read in each line of the XML file. I want to have the capability to traverse the XML file, without going in sequential order; that is, random access. I thought using moveToAttribute
would move the cursor to a node with the attribute value specified, where I can then conduct processing on its inner nodes, but this is not working out as planned.
Here's a snippet of the xml file:
<?xml version="1.0" encoding="Shift-JIS"?>
<CDs>
<Cat Type="Rock">
<CD>
<Name>Elvis Prestley</Name>
<Album>Elvis At Sun</Album>
</CD>
<CD>
<Name>Elvis Prestley</Name>
<Album>Best Of...</Album>
</CD>
</Cat>
<Cat Type="JazzBlues">
<CD>
<Name>B.B. King</Name>
<Album>Singin' The Blues</Album>
</CD>
<CD>
<Name>B.B. King</Name>
<Album>The Blues</Album>
</CD>
</Cat>
</CDs>
Here is my PHP code:
<?php
$xml = new XMLReader();
$xml->open("MusicCatalog.xml") or die ("can't open file");
$xml->moveToAttribute("JazzBlues");
print $xml->nodeType . PHP_EOL; // 0
print $xml->readString() . PHP_EOL; // blank ("")
?>
What am I doing wrong, with regards to moveToAttribute? How can I randomly access nodes using a node's attribute? I want to target node Cat Type="JazzBlues" without doing it sequentially (i.e. $xml->read()), and then process its inner nodes.
Thank you very much.