2017-02-28 43 views
1

標籤,我想獲得一個標籤,然後從以下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,讓您選擇更適合特定查找的工具。 –

回答

0

嘗試使用以下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元件

相關問題