考虑以下XML文件内容:
<catalog>
<cd>
<title>Red</title>
<artist>The Communards</artist>
</cd>
<cd>
<title>Unchain my heart</title>
<artist>Joe Cocker</artist>
</cd>
</catalog>
如何使用任何现有工具或XSLT获得以下内容?
<catalog>
<cd><title>Red</title><artist>The Communards</artist></cd>
<cd><title>Unchain my heart</title><artist>Joe Cocker</artist></cd>
</catalog>
我想做这个转换,因为我想快速地从xml文件中删除一些记录(在本例中是'cd‘)。使用单行格式会对我有所帮助。
谢谢!
发布于 2010-11-18 04:44:00
我想做这个转换,因为我想快速地从
文件中删除一些记录(在本例中是'cd‘)。使用单行格式会对我有所帮助。
我很抱歉,但这是一个错误的方法。您希望使用XSLT来操作文档中的空格,这样可以更容易地使用...不是XSLT的东西?首先删除XSLT中不需要的代码行!
基本示例(未经测试,但99%确定这将满足给定的要求):
<xsl:stylesheet version="1.0">
<!-- this is called the identity transform - it will copy the input wholesale -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- this template will provide the exception case for "cd" nodes and effectively remove them -->
<xsl:template match="cd">
<!-- do nothing with it! -->
</xsl:template>
</xsl:stylesheet>
发布于 2010-11-18 05:06:27
奇怪的重复(不是语义差异)...此样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="no" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()" name="identity">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="cd">
<xsl:text>
	</xsl:text>
<xsl:call-template name="identity"/>
<xsl:value-of select="substring('
', 1 div (position()=last()))"/>
</xsl:template>
</xsl:stylesheet>
输出:
<catalog>
<cd><title>Red</title><artist>The Communards</artist></cd>
<cd><title>Unchain my heart</title><artist>Joe Cocker</artist></cd>
</catalog>
注意:标识规则,xsl:cd
-space(修剪所有文本节点),为cd
添加新行和制表符,为最后一行添加新行。
发布于 2010-11-18 04:34:16
测试结果:
这里有一个解决方案:
<xsl:stylesheet
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output indent="no" method="xml"/>
<xsl:strip-space elements="cd title artist"/>
<xsl:template match="@*|node()">
<xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
</xsl:template>
</xsl:stylesheet>
关键是要确保输出不会自动缩进,然后指定哪些元素应该删除空格,比如cd
、title
和artist
。
https://stackoverflow.com/questions/4208749
复制相似问题