C# 用于选择下一个兄弟的 Xpath

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2092303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:26:09  来源:igfitidea点击:

Xpath for choosing next sibling

c#xmlxpath

提问by Ula Krukar

I have piece of HTML like this:

我有一段这样的 HTML:

<dt>name</dt>
<dd>value</dd>
<dt>name2</dt>
<dd>value2</dd>

I want to find all places where the structure is incorrect, meaning there is no ddtag after dttag.

我想找到结构不正确的所有地方,这意味着dd标签后没有dt标签。

I tried this:

我试过这个:

//dt/following-sibling::dt

but this doesn't work. Any suggestions?

但这不起作用。有什么建议?

采纳答案by AakashM

EDITas noted by @Gaim, my original version failed to capture a terminal dt

编辑@Gaim 指出,我的原始版本未能捕获终端dt

string xml = @"
    <root>
    <dt>name</dt>
    <dd>value</dd>
    <dt>name2</dt>
    <dt>name3</dt>
    <dd>value3</dd>
    <dt>name4</dt>
    <dt>name5</dt>
    <dd>value5</dd>
    <dt>name6</dt>
    </root>
    ";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlNodeList nodes = 
    doc.SelectNodes("//dt[not(following-sibling::*[1][self::dd])]");

foreach (XmlNode node in nodes)
{
    Console.WriteLine(node.OuterXml);
}

Console.ReadLine();

Output is those dtnodes that do not have a ddimmediately following them:

输出是那些dt没有dd紧跟其后的节点:

<dt>name2</dt>
<dt>name4</dt>
<dt>name6</dt>

What we are doing here is saying:

我们在这里所做的是说:

//dt

All dtnodes, anywhere....

所有dt节点,任何地方......

[not(following-sibling::*[1]

....such that it's notthe case that their first following sibling (whatever it is called)....

....这样他们的第一个跟随兄弟姐妹(管它叫什么)不是这样的。

[self::dd]]

...is called dd.

...被称为dd

回答by Gaim

I am not sure that I understand you but there is my solution. This XPath matches ALL <dt>which are not followed by <dd>directly. So There is test structure

我不确定我是否理解你,但有我的解决方案。这个 XPath 匹配 ALL<dt>后面没有<dd>直接跟的。所以有测试结构

<xml>
  <dt>name</dt> <!-- match -->

  <dt>name2</dt>
  <dd>value2</dd>

  <dt>name</dt>
  <dd>value</dd>

  <dt>name2</dt>  <!-- match -->
</xml>

There is the XPath

有 XPath

//dt[ name( following-sibling::*[1] ) != 'dd' ]

or

或者

//dt[  not( following-sibling::*[1]/self::dd ) ]

they do same thing

他们做同样的事情