XSL完全删除注释(包括空格)

时间:2010-12-15 05:26:21

标签: xml xslt whitespace

我有许多xml文件应遵循以下格式:

<root>
<question>What is the answer?</question>
<answer choice="A">Some</answer>
<answer choice="B">Answer</answer>
<answer choice="C">Text</answer>
</root>

但它来自一个Web界面(我无法控制输出)与评论,最终看起来像这样:

<root>
<question>What is the answer?</question>
<answer choice="A"><!--some comment
-->
Some
</answer choice="B">
<answer>

<!--some comment
     -->
    Answer
    </answer>
    <answer choice="C"><!--another comment
    -->
   Text</answer>
   </root>

删除评论后的输出结果如下:

What is the answer?
A\t


Some
B\t
Answer
C\t     
Text

现在,我设置了一个xsl表,用以删除注释:

  

<xsl:template match="comment()"/>

以及其他一些身份模板应用程序。

我会使用normalize-space(),但它会从答案文本中删除我想要的换行符。我正在寻找的是一种只删除“空白”或前后“额外”换行符的方法。有没有办法做到这一点?

另请注意:最终输出是Adobe Indesign,它使用XSLT 1.0。

[编辑 - XSL在下面]。

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

<xsl:strip-space elements="*" />

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

<xsl:template match="comment()"/>

<xsl:template match="//answer"><xsl:value-of select="@choice"/>
<xsl:text>&#09;</xsl:text><xsl:call-template name="identity"/>
</xsl:template> 

<xsl:template match="//question">
<xsl:text>00&#09;</xsl:text><xsl:call-template name="identity"/>
</xsl:template>

</xsl:stylesheet>

1 个答案:

答案 0 :(得分:4)

此样式表:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output omit-xml-declaration="yes"/>
    <xsl:strip-space elements="*" />
    <xsl:template match="@*|node()" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="comment()"/>
    <xsl:template match="@choice">
        <xsl:value-of select="concat(.,'&#x9;')"/>
    </xsl:template>
    <xsl:template match="question|answer">
        <xsl:call-template name="identity"/>
        <xsl:text>&#xA;</xsl:text>
    </xsl:template>
</xsl:stylesheet>

输出:

<root><question>What is the answer?</question>
<answer>A   Some</answer>
<answer>B   Answer</answer>
<answer>C   Text</answer>
</root>
相关问题