如何使用PHP中的moveToAttribute方法';的XMLReader类


How to use the moveToAttribute method from PHP's XMLReader class?

我对PHP的XMLReader类中的moveToAttribute方法有问题
我不想阅读XML文件的每一行。我希望能够遍历XML文件,而不需要按顺序进行;即随机接入。我认为使用moveToAttribute会将光标移动到具有指定属性值的节点,然后在那里我可以对其内部节点进行处理,但这并没有按计划进行。

以下是xml文件的一个片段:

<?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>

这是我的PHP代码:

<?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 ("")
?>

关于moveToAttribute,我做错了什么?如何使用节点的属性随机访问节点?我想以节点Cat Type="JazzBlues"为目标,而不按顺序执行(即$xml->read()),然后处理其内部节点。

非常感谢。

我认为没有办法避免XMLReader::read。XMLreader::moveToAttribute只有在XMLreader已经指向某个元素时才有效。此外,您还可以检查XMLReader::moveToAttribute的返回值,以检测可能的故障。也许可以试试这样的东西:

<?php
$xml = new XMLReader();
$xml->open("MusicCatalog.xml") or die ("can't open file");
while ($xml->read() && xml->name != "Cat"){ }
//the parser now found the "Cat"-element
//(or the end of the file, maybe you should check that)
//and points to the desired element, so moveToAttribute will work
if (!$xml->moveToAttribute("Type")){
    die("could not find the desired attribute");
}
//now $xml points to the attribute, so you can access the value just by $xml->value
echo "found a 'cat'-element, its type is " . $xml->value;
?>

这段代码应该打印文件中第一个cat元素的type属性的值。我不知道你想对这个文件做什么,所以你必须为你的想法更改代码。用于处理可以使用的内部节点:

<?php
//continuation of the code above
$depth = $xml->depth;
while ($xml->read() && $xml->depth >= $depth){
    //do something with the inner nodes
}
//the first time this Loop should fail is when the parser encountered
//the </cat>-element, because the depth inside the cat-element is higher than
//the depth of the cat-element itself
//maybe you can search for other cat-nodes here, after you processed one

我不能告诉你,如何为一个随机访问的例子重写这个代码,但我希望,我可以帮助你。