簡體   English   中英

如何使用PHP的XMLReader類中的moveToAttribute方法?

[英]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,我在做什么錯? 如何使用節點的屬性隨機訪問節點? 我想要不按順序執行(即$ xml-> read()), 而是將節點Cat Type =“ JazzBlues”作為目標,然后處理其內部節點。

非常感謝你。

我認為沒有辦法避免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元素的類型屬性的值。 我不知道您想對文件做什么,所以您必須為您的想法更改代碼。 用於處理內部節點,您可以使用:

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

我無法告訴您,如何為一個隨機訪問示例重寫此代碼,但我希望,我可以為您提供幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM