用 xquery 替换元素的值 [英] replace value of element by xquery

查看:32
本文介绍了用 xquery 替换元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了这篇关于替换给定元素值的现有帖子,但我需要进一步满足我的要求,因为我需要用另一个字符替换第一个字符.这是我找到的帖子:change value of element by xquery

I found this existing post on replacing the value of a given element, but I need to go further with my requirment in that I need to replace the first character with another. This is the post I found: change value of element by xquery

源 XML:

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

使用这个 Xquery:

Using this 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 更改为仅更改第一个字符,以便获得以下输出:

My knowledge of Xquery is only just starting grow. How do I change the above Xquery to only change the first character so that I get the below output:

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

推荐答案

使用 substring() 函数:

Use the substring() function:

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>

这篇关于用 xquery 替换元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆