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来提取枚举[@text]标签的值,其值等于属性[@name='value']中的文本。在这种情况下,期望文本“澳大利亚”。

这只是我第一次使用 xpath,任何想法都会受到赞赏。谢谢大家。

4

2 回答 2

3

利用:

/*/*/enumeration[@value = ../../*[@name = 'value']]/@text
于 2012-11-12T04:12:03.677 回答
3

使用

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

这将选择text的任何子元素的任何属性/*/restriction,其value属性等于property顶部元素的子元素的字符串值,该(property子)具有name属性,其字符串值为字符串"value"

如果您不想选择属性,而只想选择其字符串值,请使用:

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
于 2012-11-12T04:44:37.823 回答