我希望通过XSLT从XML文件中删除空标记和换行。
标准1:换行应该只在文本节点中删除,也就是说,应该保持缩进。
标准2:应该在任何操作系统上工作。
标准3: (如果可能的话)不会对XML进行任何其他更改。
XML的一个例子是:
<?xml version="1.0" encoding="UTF-8"?>
<Container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tag1>22</tag1>
<tag2>33</tag2>
<tag3/>
<minimalValue/>
<maximalValue/>
<minimalFee/>
<maximalFee/>
<tag4>This is text with a
line break.
</tag4>
</Container>的结果应该是:
<Container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<tag1>22</tag1>
<tag2>33</tag2>
<tag4>This is text with a line break.</tag4>
</Container>发布于 2017-11-15 20:58:25
要省略初始的XML声明,您应该在omit-xml-declaration中使用xsl:output属性。
要有缩进,请使用indent="yes"。
要删除空标记,您需要一个elements (match="*")模板,但需要一个谓词,该谓词要求该元素具有非空白内容([normalize-space()])。由于没有空元素的模板,因此不会复制它们。
若要删除换行,需要为text()节点提供模板,复制规范化的内容。
因此,总之,您可以使用以下脚本,比其他建议略简洁一些:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="*[normalize-space()]|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space()"/>
</xsl:template>
</xsl:stylesheet>注意,我在两个位置添加了|@*,以处理属性节点,如标识模板中的属性节点。但是,由于源XML不包含任何属性节点,所以即使没有这些添加,也可以这样做。
发布于 2017-11-15 19:45:42
我不知道这是否是最好的办法。但是,我已经通过以下模板实现了上述目标:
<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="child::node()[not(self::text())]|@*">
<xsl:if test="normalize-space(string(.)) != ''">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:if>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="normalize-space(.)"/>
</xsl:template>
</xsl:stylesheet>https://stackoverflow.com/questions/47316003
复制相似问题