0
我想刪除xml文件中的所有不必要的空格。但是,如果在arg元素之前或之後有空格,我希望在arg元素周圍保留一個空格(因爲如果它不是從頭開始的話,我不希望將參數與周圍的文本連接起來)。刪除除特定元素之前或之後的空格
輸入文件:
<?xml version="1.0" encoding="utf-8"?>
<Data>
<Text number="1">
<Title>Lazy dog jumper</Title>
<Description> The quick brown fox jumps over the lazy dog <arg format="z" />.
The quick brown fox jumps over the lazy dog <arg format="y" />. The quick brown fox jumps over the lazy dog <arg format="x" />. </Description>
</Text>
<Text number="2">
<Title> Lazy foxer</Title>
<Description>The quick brown <arg format="a" />fox <arg format="x" /><p />jumps over the lazy dog. </Description>
</Text>
</Data>
XSL文件(目前似乎插入空格不管):
<?xml version="1.0" encoding="UTF-8"?>
<!-- Remove spaces. Keep spaces around arg tags. -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
<xsl:template match="node()[local-name()='arg']">
<xsl:if test="preceding-sibling::node()[1][self::text()[not(normalize-space()) = '']]">
<xsl:text> </xsl:text>
</xsl:if>
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
<xsl:if test="following-sibling::node()[1][self::text()[not(normalize-space()) = '']]">
<xsl:text> </xsl:text>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
所需的輸出:
<?xml version="1.0" encoding="utf-8"?>
<Data>
<Text number="1">
<Title>Lazy dog jumper</Title>
<Description>The quick brown fox jumps over the lazy dog <arg format="z" />. The quick brown fox jumps over the lazy dog <arg format="y" />. The quick brown fox jumps over the lazy dog <arg format="x" />.</Description>
</Text>
<Text number="2">
<Title>Lazy foxer</Title>
<Description>The quick brown <arg format="a" />fox <arg format="x" /><p />jumps over the lazy dog.</Description>
</Text>
</Data>