使用 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
}
最佳答案
简短版本:你没有,至少不是直接的。程序员可以使用 XMLReader 将上下文编码到他们的解析算法中。
长版:PHP 的 XMLReader 是所谓的拉式解析器。拉式解析器与基于树/DOM 的解析器的不同之处在于它们可以处理文本流。换句话说,他们可以在获得整个文档之前开始解析文档。这不同于像 SimpleXML 或 DOMDocument 这样的基于树的/DOM 解析器,后者需要将整个文档加载到内存中才能执行任何操作。
优点是,如果您有一个 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)];
}
}
关于PHP XMLReader 获取父节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/513802/