2010-05-18 39 views
3

XML片段的XPath:有有一個屬性

<component name='Stipulations'> 
     <group name='NoStipulations' required='N'> 
      <field name='StipulationType' required='N' /> 
      <field name='StipulationValue' required='N' /> 
     </group> 
    </component> 
    <component name='NestedParties3'> 
     <group name='NoNested3PartyIDs' required='N'> 
      <field name='Nested3PartyID' required='N' /> 
      <field name='Nested3PartyIDSource' required='N' /> 
      <field name='Nested3PartyRole' required='N' /> 
      <group name='NoNested3PartySubIDs' required='N'> 
       <field name='Nested3PartySubID' required='N' /> 
       <field name='Nested3PartySubIDType' required='N' /> 
      </group> 
     </group> 
    </component> 
    <component name='UnderlyingStipulations'> 
     <group name='NoUnderlyingStips' required='N'> 
      <field name='UnderlyingStipType' required='N' /> 
      <field name='UnderlyingStipValue' required='N' /> 
     </group> 
    </component> 

我想是有類型的子節點「場」和一個名爲「StipulationType」所有「組」節點的子節點的節點。

這是我到目前爲止已經試過:

dictionary.XPathSelectElements("group[field[@name='StipulationType']]") 
dictionary.XPathSelectElements("group[./field[@name='StipulationType']]") 
+0

好問題(+1)。查看我的答案,通常比使用'//'更有效。 :) – 2010-05-18 01:30:55

回答

1

問題:

dictionary.XPathSelectElements("group[field[@name='StipulationType']]") 

這將選擇所有滿足謂詞的元素元素,即,它們是當前節點的子元素。

但是,您希望所有組元素(滿足謂詞) - 從XML片段中可以清楚地看到,並非所有組元素都具有相同的父元素。

溶液

評估來自隆重-祖父母XPath表達式(基於所提供的片段!):

一個示例將是:基於

component/group[field[@name='StipulationType']] 

完整文檔的結構(未提供),可能需要更多位置步驟。

避免什麼:

避免//縮寫,因爲它可能會導致(有沒有好的優化的XPath引擎),從該節點開始整個子樹(甚至是文檔)的廣泛遍歷對這個評價。

2

看起來不錯。您可能需要得到更具體一點,依賴於實現您的XPath:

//group[field[@name='StipulationType']] 

/component/group[field[@name='StipulationType']] 

應該工作

+0

我明白我做錯了什麼。我沒有將//包含在組前,這對我的源代碼xml至關重要。 (我的示例並不表示嵌套層次的真實程度如何。) – 2010-05-18 01:14:18

+0

啊。是的,當它懷疑使用'//'在各個層次進行搜索時,請記住這會導致性能損失。 – 2010-05-18 01:16:27