PHP Xpath 跟随兄弟姐妹
我正在尝试使用 xpath 来获取表的内容。
该表看起来像这样
<div>
<table>
<tr class="tableheader">
<td> Stuff </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="tableheader">
<td> Stuff </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
</table>
</div>
我正在尝试提取表头之间所有 tr[@class='indent1'] 的值,
这就是我到目前为止所拥有的:
$elements = $xPath->query("div/table/tbody/tr[@class='tableheader']");
for ($i = 0; $i < $elements->length; $i++){
print "Node: ".$elements->item($i)->nodeValue."\n";
$siblings = $xPath->query("following-sibling::tr[@class='indent1']", $elements->item($i));
foreach ($siblings as $sibling) {
print "\tSibling: ".$sibling->nodeValue."\n";
}
}
预期输出是
Node: Stuff
Sibling: Contents
Sibling: Contents
Node: Stuff
Sibling: Contents
Sibling: Content
s
而不是打印 ALL tr class="indent1s “对于每一个。
谢谢。
I'm trying to use xpath to get the contents of a table.
The table looks like this
<div>
<table>
<tr class="tableheader">
<td> Stuff </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="tableheader">
<td> Stuff </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
<tr class="indent1">
<td> Contents </td>
</tr>
</table>
</div>
I'm trying to pull the value of all tr[@class='indent1'] between table headers
this is what I have so far :
$elements = $xPath->query("div/table/tbody/tr[@class='tableheader']");
for ($i = 0; $i < $elements->length; $i++){
print "Node: ".$elements->item($i)->nodeValue."\n";
$siblings = $xPath->query("following-sibling::tr[@class='indent1']", $elements->item($i));
foreach ($siblings as $sibling) {
print "\tSibling: ".$sibling->nodeValue."\n";
}
}
The expected output is
Node: Stuff
Sibling: Contents
Sibling: Contents
Node: Stuff
Sibling: Contents
Sibling: Content
s
Instead it is printing ALL tr class="indent1s" for each one.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:
好吧,也许这对您有帮助。只需获取每个兄弟并使用 PHP 检查属性:
您的总体目标是什么?如果您只想打印出节点,则使用 SAX 处理结构会更合适更容易(SAX 与 PHP)。
或者也许 XSLT 但我无法帮助你。
EDIT:
OK maybe this helps you. Just get every sibling and check the attributes with PHP:
What is your goal in general? If you just want to print out the nodes, processing the structure with SAX would be more appropriate and easier (SAX with PHP).
Or maybe XSLT but I cannot help you with that.