2012-04-10 109 views
4

對於XSLT模板,我需要一個XPath表達式來定位具有特定子元素但沒有文本節點的元素。查找具有特定子元素但沒有文本節點的元素

<!-- 1: matches --> 
<a><b/></a> 

<!-- 2: does not match --> 
<a>foo bar quux<b/></a> 

<!-- 3: does not match --> 
<a>whatever <b/> further text</a> 

<!-- 4: does not match --> 
<a>whatever <b/> further text <b/></a> 

<!-- 5: does not match --> 
<a><x/><b/></a> 

<!-- 6: does not match --> 
<a>foo bar quux</a> 

我想出了a[*[1 = last() and name() = 'b']],但隨後情況2或3時,匹配他們不應該。原因當然是,*選擇元素並且不關心文本節點。那我該怎麼做呢?

回答

2

你可以只使用

a[count(*)=1 and b and not(text())] 

如果你只是在尋找一個B,沒有其他的元素,沒有文字。請記住,如果您在xml中有回車符,則某些處理器會將其作爲文本。

+0

或者,如果你可以接受多個B的,一[B,而不是(* [名稱()=」 b'])而不是(文字())]​​ – Woody 2012-04-10 08:42:15

+0

完美,非常感謝! – 2012-04-10 08:44:09

+0

@JensBannmann:你可能會對更短,更緊湊的表達感興趣:) – 2012-04-10 12:24:30

1

較短

a[b and not(text() or *[2])] 

這個選擇每a孩子當前節點(上下文節點)的具有b孩子,沒有任何文本子節點或第二子元素。

更短,如果你也不想有任何PI或發表評論的孩子

a[b and not(node()[2])] 
相關問題