有了这个输入
<?xml version="1.0" encoding="UTF-8"?> <data>
This is a senstence
this is another sentence
<section>
<!--comment --><h2>my H2</h2> <p>some paragraph</p> <p>another paragraph</p>
</section> </data>
我需要应用 XSL 样式表来获取纯文本,尊重换行符,并删除前面的空格。所以,在网上搜索了几个样本后,我尝试了这个,但它对我不起作用。对不起,我不熟悉 XSL,我想我会问。
尝试过 XSL,但它不起作用。有任何想法吗?
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:strip-space elements="*" />
<xsl:template match ="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="h1|h2">
<xsl:text>
</xsl:text>
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
这是应用 XSL 后的输出。
如您所见,全部为一行,而不是回车。
This is a sentence this is another sentence m H2some paragraphTanother paragraph
这是我想要的输出。 H1|H2|H3 中的文本前后应有换行符。
This is a sentence
this is another sentence
my H2
some paragraph
another paragraph
最佳答案
您需要一个 xml:space="preserve"
保持回车的属性xml:text
,并且在h1
的内容前后需要回车和 h2
标签:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<xsl:strip-space elements="*" />
<xsl:template match ="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="h1|h2">
<xsl:text xml:space="preserve">
</xsl:text>
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
<xsl:text xml:space="preserve">
</xsl:text>
</xsl:template>
</xsl:stylesheet>
在我的情况下,初始文本(
This is a senstence
、 this is another sentence
)在单独的行上正确输出(使用 Visual Studio 2012 执行 XSLT)。你只写了
h
标签应该添加回车符 - 在您的示例中 some paragraph
和 another paragraph
在 p
标签,所以没有添加回车,它们在同一行输出。
关于xslt - 如何使用 XSL 获取纯文本和换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18125287/