由替换的XQuery元件的值(replace value of element by xquery)

2019-09-20 15:39发布

我发现替换给定元素的值,这个现有的职位,但我需要用我在需求量的,我需要用另一个替换的第一个字符走得更远。 这是我找到的帖子: 通过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>

Answer 1:

使用子串()函数

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>


文章来源: replace value of element by xquery
标签: xml xslt xquery