PHP XMLReader获取父节点?

Zaj*_*aje 2 php parsing xmlreader

在使用XMLReader方法解析XML文件时,如何获取元素的父节点?

$xml = new XMLReader();
$xml->XML($xmlString);
while($xml->read())
{

$xml->localName; // gives tag name
$xml->value; // gives tag value

// how do I access the parent of this element 
}
Run Code Online (Sandbox Code Playgroud)

Ala*_*orm 10

简短版本:你没有,至少不是直接的.程序员可以使用XMLReader将上下文编码到解析算法中.

长版本:PHP的XMLReader就是所谓的拉解析器.Pull解析器与基于树/ dom的解析器的不同之处在于它们可以处理文本流.换句话说,他们可以在拥有整个文档之前开始解析文档.这与基于树的/ DOM解析器(如SimpleXML或DOMDocument)不同,后者需要在可以执行任何操作之前将整个文档加载到内存中.

优点是,如果你有一个75MB的XML文件,你不需要75MB的空闲RAM来处理它(就像你使用基于树的解析器一样).权衡是拉解析器永远不会有整个文档的上下文.唯一具有他们恰好正在处理的节点的上下文.

另一种思考方式是基于树/ dom的解析器必须知道文档的每个部分,因为它不知道你要求它的内容.但是,你和pull解析器做了不同的安排.它会不断地向你扔节点,并让你自己处理它们的内容.

这里有一些示例代码(希望)接近您所追求的内容.

$xml = new XMLReader(); 
$xml->open('example.xml');
$last_node_at_depth = array();
while($xml->read())
{               
    //stash the XML of the entire node in an array indexed by depth
    //you're probably better off stashing exactly what you need from
    $last_node_at_depth[$xml->depth] = $xml->readOuterXML();

    $xml->localName; // gives tag name
    $xml->value;     // gives tag value     

    //so, right now we're at depth n in the XML document.  depth n-1 
    //would be our parent node
    if ($xml->depth > 0) {
        //gives the fragment that starts with the parent node       
        $last_node_at_depth[($xml->depth-1)];   
    }
}
Run Code Online (Sandbox Code Playgroud)