XML&;XPath表达式

XML&;XPath表达式,xml,xpath,Xml,Xpath,假设我有这个XML: <root> <A></A> <B></B> <C>one</C> <C>two</C> <C>three</C> <D></D> </root> 但是这会删除所有的C节点,所以现在我必须添加一个我想要保留的C节点的索引 //*[not(ancestor-or

假设我有这个XML:

<root>
    <A></A>
    <B></B>
    <C>one</C>
    <C>two</C>
    <C>three</C>
    <D></D>
</root>
但是这会删除所有的C节点,所以现在我必须添加一个我想要保留的C节点的索引

//*[not(ancestor-or-self::C)] exept for C[1]
如果我选择索引1,我如何将其容纳,以便输出为:

<root>
   <A></A>
   <B></B>
   <C>one</C>
   <D></D>
</root>
或者,如果我选择索引2:

<root>
   <A></A>
   <B></B>
   <C>two</C>
   <D></D>
</root>
希望我说得够清楚:p
thx

我认为这取决于你对“索引”的定义。如果将“索引”定义为具有n-1个C同级的C,则可以执行以下操作:

先显示一个(然后删除所有)

/root/*[not(name() = 'C'  and count(preceding::C) >= 1)]
仅显示第二个

/root/*[not(name() = 'C' and (count(preceding::C) < 1 or count(preceding::C) > 1))]
/root/*[不是(name()=“C”和(count(preference::C)<1或count(preference::C)>1))]
(我用:仅供参考)为什么除了?除了这些元素之外,你还有其他元素,然后你添加其中的一些元素:

//*[not(ancestor-or-self::C)]|//C[1]/descendant-or-self::*
使用

//*[not(self::c and not(count(preceding-sibling::c) = $ind - 1))]

其中,$ind是要选择的
c
元素的所需位置(基于1)。

@Rise\u反对:you's wellcome。好问题,+1。请参阅我的答案,以获得一个简单的XPath表达式,该表达式精确选择所需节点。
//*[not(self::c and not(count(preceding-sibling::c) = $ind - 1))]