XPath获取兄弟节点的父节点值

3

目前我有一些类似于这样的xml结构:

<element type="Input" name="nationality">
   <property i18n="true" text="Nationality" prefix="person.nationality."
    name="caption">caption</property>
   <property i18n="true" text="Nationality" prefix="person.nationality."
    name="desc">desc</property>
   <property name="visible">1</property>
   <property name="mandatory">0</property>
   <property name="value">AUS</property>
   <restriction prefix="country." base="String">
    <enumeration text="Albania" value="ALB" />
    <enumeration text="Algeria" value="DZA" />
    <enumeration text="Argentina" value="ARG" />
    <enumeration text="Australia" value="AUS" />
    <enumeration text="Austria" value="AUT" />
    <enumeration text="Bahrain" value="BHR" />
   </restriction>
</element>

我想问一下,是否有办法使用xpath提取属性[@name='value']中值为"Australia"的枚举[@text]标签的值。这是我第一次使用xpath,希望能给我一些建议。谢谢大家!
2个回答

3

使用:

/*/*/enumeration[@value = ../../*[@name = 'value']]/@text

3

用途:

/*/restriction/*[@value = /*/property[@name='value']]/@text

这个选择器选择任何一个/*/restriction的子元素中,其value属性等于顶级元素的一个property子元素的字符串值(该property子元素拥有一个name属性,其字符串值是"value"),然后选择该子元素的任何text属性。如果你只需要选取属性的字符串值而非属性本身,则使用以下方法:
string(/*/restriction/*[@value = /*/property[@name='value']]/@text)

XSLT基于验证:

 <xsl:template match="/">
  <xsl:value-of select=
  "/*/restriction/*[@value = /*/property[@name='value']]/@text"/>
==========
  <xsl:value-of select=
  "string(/*/restriction/*[@value = /*/property[@name='value']]/@text)"/>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于提供的XML文档时:
<element type="Input" name="nationality">
   <property i18n="true" text="Nationality" prefix="person.nationality."
    name="caption">caption</property>
   <property i18n="true" text="Nationality" prefix="person.nationality."
    name="desc">desc</property>
   <property name="visible">1</property>
   <property name="mandatory">0</property>
   <property name="value">AUS</property>
   <restriction prefix="country." base="String">
    <enumeration text="Albania" value="ALB" />
    <enumeration text="Algeria" value="DZA" />
    <enumeration text="Argentina" value="ARG" />
    <enumeration text="Australia" value="AUS" />
    <enumeration text="Austria" value="AUT" />
    <enumeration text="Bahrain" value="BHR" />
   </restriction>
</element>

这两个XPath表达式将针对上述文档进行评估,并将评估结果的字符串值(适当加以限定)复制到输出中:

Australia
==========
  Australia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接