如何使用XSL获取纯文本和换行符

Jos*_*eon 5 xslt

有了这个输入

<?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>
Run Code Online (Sandbox Code Playgroud)

我需要应用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>
Run Code Online (Sandbox Code Playgroud)

这是应用XSL后的输出.如你所见,它的所有一行,而不是回车.

This is a sentence this is another sentence m H2some paragraphTanother paragraph
Run Code Online (Sandbox Code Playgroud)

这是我想要的输出.H1 | H2 | H3中的文本应该在前后换行.

This is a sentence 
this is another sentence 

my H2

some paragraph
another paragraph
Run Code Online (Sandbox Code Playgroud)

MiM*_*iMo 4

需要一个xml:space="preserve"属性来维护 内的回车符,并且和标签xml:text的内容前后都需要一个回车符:h1h2

<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>
Run Code Online (Sandbox Code Playgroud)

在我的例子中,初始文本 ( This is a senstence, this is another sentence) 在单独的行上正确输出(使用 Visual Studio 2012 执行 XSLT)。

您写道,只有h标签应该添加回车符 - 在您的示例中some paragraph并且another paragraph位于p标签中,因此不添加回车符,并且它们在同一行上输出。