Xquery append text to tag values depending of the element type

早过忘川 提交于 2019-12-13 05:51:42

问题


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(), '&#xA;')

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!