DomXML xpath接下来我该怎么办?

I have this code:

$reader = new DOMDocument();
$reader->loadHTML($shell);
$xpath = new DomXPath($reader);
$xpath->registerNamespace('html','http://www.w3.org/1999/xhtml');
$res = $xpath->query('descendant-or-self::*[contains(@class,"content")]');
print_r($res);

$shell is just a variable containing the following html code:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Language" content="en-us" />

        <title>Hello World</title>
    </head>

    <body>
        <div class="content">
            Hello World!!
        </div>
    </body>
</html>

If I am correct the xpath query:

descendant-or-self::*[contains(@class,"content")]

is supposed to get the div with the class "content". However when I print the array all I see is an empty object:

DOMNodeList Object
(
)

Does this mean that the query didnt work? Is the DomXPath query language different to the SimpleXML Xpath one, because the query works with SimpleXML?

If it is working how do I view and modify the matched nodes?

2个回答

print_r - ing a DOMNodeList (or any of the DOM-classes) doesn't do you much good: they're mostly implemented at C / Libxml2 level, and not natively exposed to PHP. As far as I can tell, this will work, add this after your query, and see if you get results:

foreach($res as $node){
        var_dump($node->ownerDocument->saveXML($node));
}
dousha1831
dousha1831 我要说看php.net/manual/en/class.domelement.php中的DOMElement规范,你可能正在寻找setAttribute函数,childNodes属性(也是一个DOMNodeList),nodeValue等.API 需要一些习惯,但它大部分是商定的API,所以任何DOM引物(PHP或其他)很可能会让你对它的工作有一个很好的洞察力(并检查PHP手册中的注释)。
大约 10 年之前 回复
douchen9569
douchen9569 谢谢,查询正在运行。 那么我将如何编辑匹配的节点属性和数据呢?
大约 10 年之前 回复



我想你想要像这样的somthiing:</ p>

// * [@ class ='content'] </ code> </ p>

这将获得具有类内容的任何标记。</ p>

它将更具可读性 得到任何div:</ p>

// div [@ class ='content'] </ code> </ p>

在xpath中,你使用 // </ code>运算符可以在dom中的任何级别获取标记。 它将匹配所有。</ p>
</ div>

展开原文

原文

I am thinking you want somthiing like this:

//*[@class='content']

This will get any tag with the class content.

It will be slightly more readable to just get the any div:

//div[@class='content']

In xpath, you use the // operator to grab a tag at any level in the dom. It will match them all.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐