问题
I need to get the values of some elements and then some text needs to be added depending on the element, for example:
<elementType>a</elementType>
<otherElementType>b</otherElementType>
<elementType>c</elementType>
<elementType>d</elementType>
$doc//*[self::elementType or self::otherElementType]/string()
"a"
"b"
"c"
"d"
this returns the values but I don´t know how to get the values like this:
"a is an elementType"
"b is an otherElementType"
"c is an elementType"
"d is an elementType"
回答1:
Use:
//*[self::elementType or self::otherElementType]
/concat(., ' is a ', name(), '
')
When this expression is evaluated against the following XML document (the provided malformed fragment -- corrected):
<t>
<elementType>a</elementType>
<otherElementType>b</otherElementType>
<elementType>c</elementType>
<elementType>d</elementType>
</t>
The wanted, correct result is produced:
a is a elementType
b is a otherElementType
c is a elementType
d is a elementType
回答2:
You might like to look at XSLT with its rule-based processing, which seems to match the way you are thinking about your requirements:
Use
<xsl:apply-templates select="*"/>
to process all the elements, and then separate template rules to say how each kind of element is to be processed:
<xsl:template match="elementType">
do one thing
</xsl:template>
<xsl:template match="otherElementType">
do a different thing
</xsl:template>
来源:https://stackoverflow.com/questions/12241824/xquery-append-text-to-tag-values-depending-of-the-element-type