用xquery替换元素的值



我发现了这篇关于替换给定元素值的现有文章,但我需要进一步满足我的要求,因为我需要用另一个字符替换第一个字符。这是我发现的帖子:通过xquery更改元素的值

源XML:

<?xml version="1.0" encoding="UTF-8"?>
<category>
    <catid>1</catid>
    <cattext>sport</cattext>
</category>

使用此Xquery:

declare namespace local = "http://example.org";
declare function local:copy-replace($element as element()) {
  if ($element/self::cattext)
  then <cattext>art</cattext>
  else element {node-name($element)}
               {$element/@*,
                for $child in $element/node()
                return if ($child instance of element())
                       then local:copy-replace($child)
                       else $child
               }
};
local:copy-replace(/*)

给出以下输出:

<?xml version="1.0" encoding="UTF-8"?>
<category>
    <catid>1</catid>
    <cattext>art</cattext>
</category>

我对Xquery的了解才刚刚开始增长。如何将上面的Xquery更改为只更改第一个字符,以便获得以下输出:

<?xml version="1.0" encoding="UTF-8"?>
<category>
    <catid>1</catid>
    <cattext>9port</cattext>
</category>

使用substring()函数

declare namespace local = "http://example.org";
declare function local:copy-replace($element as element()) {
  if ($element/self::cattext)
  then <cattext>9{substring($element,2)}</cattext>
  else element {node-name($element)}
               {$element/@*,
                for $child in $element/node()
                return if ($child instance of element())
                       then local:copy-replace($child)
                       else $child
               }
};
local:copy-replace(/*)

当此查询应用于所提供的XML文档时:

<category>
    <catid>1</catid>
    <cattext>sport</cattext>
</category>

生成所需的正确结果:

<category>
    <catid>1</catid>
    <cattext>9port</cattext>
</category>

使用XSLT进行相同的转换要容易得多:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>
 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
 </xsl:template>
 <xsl:template match="cattext/text()">
  <xsl:text>9</xsl:text><xsl:value-of select="substring(., 2)"/>
 </xsl:template>
</xsl:stylesheet>

当此转换应用于同一XML文档(如上)时,会再次产生所需的正确结果

<category>
   <catid>1</catid>
   <cattext>9port</cattext>
</category>

最新更新