2

特定の要素の値の置換に関するこの既存の投稿を見つけましたが、最初の文字を別の文字に置き換える必要があるという要件をさらに進める必要があります。これは私が見つけた投稿です: 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>
4

1 に答える 1

3

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>
于 2012-08-02T03:05:36.580 に答える