PHP XMLReader获取父节点?

时间:2009-02-04 23:03:57

标签: 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 
}

3 个答案:

答案 0 :(得分: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)];   
    }
}

答案 1 :(得分:1)

我已经开始使用XMLReader的expand()函数了。它给出了当前xml标记的DOM表示。我在父节点上使用了expand(),它给了我父元素的DOM元素,然后使用通常的DOMDocument()解析方法提取子值。

//usage
$xml = new XMLReader();
$xml = $xml->XML($xmlResponse);
while($xml->read())
{
$parent = $xml->expand();

$firstChildValue = $parent->getElementsByTagName('child')->item(0)->nodeValue;
}

使用expand函数只将大部分XML加载到内存中,而不是将整个XML加载到内存中。

答案 2 :(得分:0)

我想你想要:XMLReader::moveToElement

相关问题