XPath - 如何选择节点的子元素?

10

我有一个包含XHTML表格的XmlDocument。我想循环遍历它,以便逐行处理表格单元格,但是下面的代码返回嵌套循环中的所有单元格,而不仅仅是当前行的单元格:

XmlNodeList tableRows = xdoc.SelectNodes("//tr");
foreach (XmlElement tableRow in tableRows)
{
    XmlNodeList tableCells = tableRow.SelectNodes("//td");
    foreach (XmlElement tableCell in tableCells)
    {
        // this loops through all the table cells in the XmlDocument,
        // instead of just the table cells in the current row
    }
}

我做错了什么?谢谢

1个回答

18

在内部路径前使用"."来表明您想从当前节点开始。以"/"开头的路径总是从xml文档的根节点开始搜索,即使您将其指定在子节点上也是如此。

因此:

XmlNodeList tableCells = tableRow.SelectNodes(".//td");

甚至更多

XmlNodeList tableCells = tableRow.SelectNodes("./td");

因为那些 <td> 很可能直接在那个 <tr> 下面。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接