如何获得没有具体的祖先和后代使用REXML

问题描述:

标签,我想获得一个标签,然后从以下XML在B标签,但我想删除第二个标记:如何获得没有具体的祖先和后代使用REXML

......many other tags. 
<A>abc</A> 
<A> <<==== I want to remove this A tag from result. 
    <B>def 
    <A>foo</A> 
    <A>hoge</A> 
    <A>bar</A> 
    </B> 
</A> 
....... 

我使用这个XPath:

//*[self::A[not(descendant::B) or self::B]] 

但是这个XPath就在B标签的标签内两次:

<A>abc</A> 
    <B>def 
     <A>foo</A> 
     <A>hoge</A> 
     <A>bar</A> 
    </B> 
    <A>foo</A> 
    <A>hoge</A> 
    <A>bar</A> 

然后,我写了这个Xpath的,但它不工作:

//*[self::A[not(descendant::B or ancestor::B) or self::B]] 

我想要得到这样的结果:

<A>abc</A> 
    <B>def 
     <A>foo</A> 
     <A>hoge</A> 
     <A>bar</A> 
    </B> 

....... 

我该如何解决这个问题?

+0

我推荐使用[引入nokogiri] (http://www.nokogiri.org)通过REXML。虽然REXML附带Ruby,但Nokogiri速度更快并且是事实标准。它还支持使用CSS选择器和XPath,让您选择更适合特定查找的工具。 –

尝试使用以下XPath表达式:

//*[self::A[not(./B) and not(./parent::B)] or self::B] 

输出:

'<A>abc</A>' 
'<B>def 
    <A>foo</A> 
    <A>hoge</A> 
    <A>bar</A> 
    </B>' 

self::A[not(./B) and not(./parent::B)]意味着A不具有直接子或父B元件