PHP DOMElement :: getElementsByTagName - 无论如何只获得直接匹配的孩子?

rr.*_*rr. 7 php xml dom

有没有办法只检索通过调用DOMElement :: getElementsByTagName找到的直接子项?例如,我有一个包含category元素的XML文档.该category元素具有子类别元素(具有相同的结构),如:

<category>
    <id>1</id>
    <name>Top Level Category Name</name>
    <subCategory>
        <id>2</id>
        <name>Sub Category Name</name>
    </subCategory>
    ...
</category>
Run Code Online (Sandbox Code Playgroud)

如果我有代表顶级类别的DOMElement,

$topLevelCategoryElement->getElementsByTagName('id');
Run Code Online (Sandbox Code Playgroud)

将返回一个列表,其中包含所有'id'元素的节点,其中我只需要顶级的元素.在使用XPath之外的任何方法都可以做到这一点?

Art*_*cto 16

恐怕不是.您必须遍历子项或使用XPath.

for ($n = $parent->firstChild; $n !== null; $n = $n->nextSibling) {
    if ($n instanceof DOMElement && $n->tagName == "xxx") {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

XPath和XML文件的示例:

$xml = ...;
$d = new DOMDocument();
$d->loadXML($xml);
$cat = $d->getElementsByTagName("subCategory")->item(0);
$xp = new DOMXpath($d);
$q = $xp->query("id", $cat); //note the second argument
echo $q->item(0)->textContent;
Run Code Online (Sandbox Code Playgroud)

2.

  • @Ella它不是一个数组,它是一个`DOMNodeList`对象,它实现了`Traversable`并且可以用`foreach'迭代 (2认同)

Kri*_*ris 11

这样的事应该做

/**
 * Traverse an elements children and collect those nodes that
 * have the tagname specified in $tagName. Non-recursive
 *
 * @param DOMElement $element
 * @param string $tagName
 * @return array
 */
function getImmediateChildrenByTagName(DOMElement $element, $tagName)
{
    $result = array();
    foreach($element->childNodes as $child)
    {
        if($child instanceof DOMElement && $child->tagName == $tagName)
        {
            $result[] = $child;
        }
    }
    return $result;
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加了instanceof DOMElement检查