2014-03-07 79 views
0

我的要求是一样转义字符XML转换

输入: -

<request> <attribute> <attributeName>Name</attributeName> <attributeValue>a &amp; b</attributeValue> </attribute> <attribute> <attributeName>Name1</attributeName> <attributeValue>b</attributeValue> </attribute> </request>

输出: -

<request> <attribute> <attributeName>Name</attributeName> <attributeValue>a & b</attributeValue> </attribute> <attribute> <attributeName>Name1</attributeName> <attributeValue>b</attributeValue> </attribute> </request>

转义字符,进来的标签n个和我需要在运行时替换所有的属性元素类型是无界的。 我怎样才能在xslt中实现相同?

+3

所需的输出格式不正确。 XML中不能有非转义的&符号字符。 – mzjn

+0

对不起@mzjn,但我不同意你的看法。 '' –

+0

@NickG:当然,您可以使用CDATA部分转义字符。但是这个问题中所要求的结果有一个赤裸裸的符号,这使得它不合格。 – mzjn

回答

0

这产生你想要的输出! (让我知道如果它不是!)

身份模板,复制所有元素。

ampText模板,查找在文本中的所有字母包含&amp;

字母模板迭代(递归)的所有文本,并取代的&amp;所有实例&

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
> 
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" /> 

<xsl:template name="identity" match="* | @*"> 
    <xsl:copy> 
     <xsl:apply-templates select="* | @* | text()" /> 
    </xsl:copy> 
</xsl:template> 

<xsl:template name="ampText" match="text()[contains(.,'&amp;')]"> 
    <xsl:call-template name="letters"> 
     <xsl:with-param name="text" select="." /> 
    </xsl:call-template> 
</xsl:template> 

<xsl:template name="letters"> 
    <xsl:param name="text" select="'Some text'" /> 
    <xsl:if test="$text != ''"> 
    <xsl:variable name="letter" select="substring($text, 1, 1)" /> 
    <xsl:choose> 
     <xsl:when test="$letter = '&amp;'"> 
      <xsl:text disable-output-escaping="yes"><![CDATA[&]]></xsl:text> 
     </xsl:when> 
     <xsl:otherwise><xsl:value-of select="$letter" /></xsl:otherwise> 
    </xsl:choose> 
    <xsl:call-template name="letters"> 
     <xsl:with-param name="text" select="substring-after($text, $letter)" /> 
    </xsl:call-template> 
    </xsl:if> 
</xsl:template> 

</xsl:stylesheet> 
+0

感谢尼克,它的工作。感谢大家的好评和最佳回应。 – user3384223