2010-05-18 45 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