gpt4 book ai didi

XSLT 1.0 : escaping double quotes

转载 作者:行者123 更新时间:2023-12-04 17:56:58 24 4
gpt4 key购买 nike

我有一个遵循此方案的 XML 文件:

<translationData>
<product>
<attributeValue>
<value>1/4"</value>
<value1>1/4"</value1>
<currentValue>aaaa;bbbb</currentValue>
</attributeValue>
</product>
</translationData>

因为“currentValue”中的分号,我需要转义“value”中的分号和双引号。我可以通过将所有文本放在 qoutes 中来转义分号,如下所示:

XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />

<xsl:param name="delim" select="';'" />
<xsl:param name="quote" select="'&quot;'" />
<xsl:param name="break" select="'&#xA;'" />

<xsl:template match="/">
<xsl:apply-templates select="translationData/product/attributeValue" />
</xsl:template>

<xsl:template match="attributeValue">
<xsl:apply-templates />
<xsl:if test="following::*">
<xsl:value-of select="$break" />
</xsl:if>
</xsl:template>


<xsl:template match="*">
<!-- remove normalize-space() if you want keep white-space at it is -->

<xsl:value-of select="concat($quote, translate(.,'&quot;','\&quot;'), $quote)" />
<xsl:if test="following-sibling::*">
<xsl:value-of select="$delim" />
</xsl:if>
</xsl:template>

<xsl:template match="text()" />
</xsl:stylesheet>

但不知何故输出是:

"1/4\";"1/4\";"aaaa;bbbb"

代替

"1/4\"";"1/4\"";"aaaa;bbbb"

我哪里错了?

我是 XML 和 XSLT 的新手,没有发现任何处理这种特定情况的问题。


XSLT 代码来自@Tomalak 对另一个问题的回答。见here

最佳答案

translate() 函数只会用另一个单个 字符替换每个单个字符。

要用两个字符的字符串\"替换单个字符",您需要使用命名的递归模板,或者-如果您的处理器支持它-扩展函数例如EXSLT str:replace() .

这是一个使用递归模板的例子:

...

<xsl:template match="*">
<xsl:text>"</xsl:text>
<xsl:call-template name="replace">
<xsl:with-param name="text" select="."/>
</xsl:call-template>
<xsl:text>"</xsl:text>
<xsl:if test="position()!=last()">
<xsl:text>;</xsl:text>
</xsl:if>
</xsl:template>

...

<xsl:template name="replace">
<xsl:param name="text"/>
<xsl:param name="searchString">"</xsl:param>
<xsl:param name="replaceString">\"</xsl:param>
<xsl:choose>
<xsl:when test="contains($text,$searchString)">
<xsl:value-of select="substring-before($text,$searchString)"/>
<xsl:value-of select="$replaceString"/>
<!-- recursive call -->
<xsl:call-template name="replace">
<xsl:with-param name="text" select="substring-after($text,$searchString)"/>
<xsl:with-param name="searchString" select="$searchString"/>
<xsl:with-param name="replaceString" select="$replaceString"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>

...

关于XSLT 1.0 : escaping double quotes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39740142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com