PHP DOMElement :: getElementsByTagName - 反正得到刚才匹配的孩子? [英] PHP DOMElement::getElementsByTagName - Anyway to get just the immediate matching children?

查看:119
本文介绍了PHP DOMElement :: getElementsByTagName - 反正得到刚才匹配的孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < category> 
< id> 1< / id>
< name>顶级类别名称< / name>
< subCategory>
< id> 2< / id>
< name>子类别名称< / name>
< / subCategory>
...
< / category>

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

  $ topLevelCategoryElement-> getElementsByTagName('id'); 

将返回一个包含所有'id'元素的节点的列表,其中我只想要一个顶级。任何方式在使用XPath之外做这个事情?

解决方案

我不怕。您必须遍历孩子或使用XPath。

  for($ n = $ parent-> firstChild; $ n $ == null; $ n = $ n-> nextSibling){
if($ n instanceof DOMElement&& $ n> tagName ==xxx){
// ...
}
}

使用XPath和您的XML文件的示例:

  $ xml = ...; 
$ d = new DOMDocument();
$ d-> loadXML($ xml);
$ cat = $ d-> getElementsByTagName(subCategory) - > item(0);
$ xp = new DOMXpath($ d);
$ q = $ xp-> query(id,$ cat); //注意第二个参数
echo $ q-> item(0) - > textContent;

给出 2


is there a way to retrieve only the immediate children found by a call to DOMElement::getElementsByTagName? For example, I have an XML document that has a category element. That category element has sub category elements (which have the same structure), like:

<category>
    <id>1</id>
    <name>Top Level Category Name</name>
    <subCategory>
        <id>2</id>
        <name>Sub Category Name</name>
    </subCategory>
    ...
</category>

If I have a DOMElement representing the top level category,

$topLevelCategoryElement->getElementsByTagName('id');

will return a list with the nodes for all 'id' elements, where I want just the one from the top level. Any way to do this outside of using XPath?

解决方案

I'm afraid not. You'll have to iterate through the children or use XPath.

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

Example with XPath and your XML file:

$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;

gives 2.

这篇关于PHP DOMElement :: getElementsByTagName - 反正得到刚才匹配的孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆