XSLT output formatting: keep line breaks, remove indent

那年仲夏 提交于 2019-12-04 06:34:14

问题


Here's my XML:

<doc>
  <article>
    <texte>
      <notes>-</notes>
      <content>
        <title>T 1</title>
        <argument>Arg 1</argument>
        <p>Paragraph 1.1</p>
        <p>Paragraph 1.2</p>
        <p>Paragraph <i>1.3</i></p>
        <short-author>FB</short-author>
      </content>
      <notes>-</notes>
      <content>
        <title>T2</title>
        <p>Paragraph 2.1</p>
        <short-author>JD</short-author>
      </content>
      <notes>-</notes>
      <content>
        <title>T3</title>
        <argument>Arg 3</argument>
        <p>Paragraph 3.1</p>
        <short-author>NC</short-author>
      </content>
    </texte>
  </article>
</doc>

This is the XSL (thanks Dimitre):

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/>


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

<xsl:template match="@class" />

  <xsl:template match="node()[not(self::doc|self::texte|self::author|self::style|self::span)]|@*" >
    <xsl:copy>
      <xsl:apply-templates select="node()[not(self::author)]|@*"/>
    </xsl:copy>
  </xsl:template>



</xsl:stylesheet>

So far so good. I'd like to

  • preserve the line-breaks and
  • remove the indentation

When I set output indent to "yes", I get both, line-breaks and indents. When I set output indent to "no", I get none.

Thank you!


回答1:


If you don't strip and don't indent, but transform white space text nodes to a line break, as in

<xsl:stylesheet version="1.0"  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

<xsl:template match="@class" />

  <xsl:template match="node()[not(self::doc|self::texte|self::author|self::style|self::span)]|@*" >
    <xsl:copy>
      <xsl:apply-templates select="node()[not(self::author)]|@*"/>
    </xsl:copy>
  </xsl:template>

<xsl:template match="text()[not(normalize-space())]">
    <xsl:text>&#10;</xsl:text>
</xsl:template>

</xsl:stylesheet>

then the result is hopefully what you want.



来源:https://stackoverflow.com/questions/34509761/xslt-output-formatting-keep-line-breaks-remove-indent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!