这是我的XML:
<section>
<para>part1 <breakline/> part2
<list>
<para>list1 </para>
<para>list2 </para>
</list>
</para>
<para>before_line_break <breakline/> after</para>
<para>para3</para>
</section>
预期产出:
part1
part2
before_line_break
after
para3
我想要“part2”但不是“list1”和“list2”
等效的HTML文件是:
<html>
<body>
part1 <br/>
part2 <br/>
before_line_break <br/>
after <br/>
para3 <br/>
</body>
</html>
我在xsl文件中尝试过很多东西。这只是一个例子(当然不起作用):
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<xsl:for-each select="section/para">
<xsl:value-of select="."/>
<br/>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
我应该如何更改我的XSL文件以获得预期的输出? 在此先感谢您的帮助。
答案 0 :(得分:2)
以此为出发点:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates select="section/para"/>
</body>
</html>
</xsl:template>
<xsl:template match="para">
<xsl:apply-templates select="text()|breakline"/>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="."/>
<!-- print br if text() is at end of para -->
<xsl:if test="position()=last()">
<br/>
</xsl:if>
</xsl:template>
<!-- replace breakline with br -->
<xsl:template match="breakline">
<br/>
</xsl:template>
<!-- mute list -->
<xsl:template match="list/para"/>
</xsl:stylesheet>
答案 1 :(得分:2)
这可能是最短的解决方案 - 只有两个模板,没有条件,没有xsl:for-each
:
<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="/*">
<html>
<body>
<xsl:apply-templates select="para/text()[normalize-space()]"/>
</body>
</html>
</xsl:template>
<xsl:template match="para/text()">
<xsl:value-of select="concat('
', normalize-space(.))"/><br />
</xsl:template>
</xsl:stylesheet>
在提供的XML文档上应用此转换时:
<section>
<para>part1 <breakline/> part2
<list>
<para>list1 </para>
<para>list2 </para>
</list>
</para>
<para>before_line_break <breakline/> after</para>
<para>para3</para>
</section>
产生了想要的正确结果:
<html>
<body>
part1<br>
part2<br>
before_line_break<br>
after<br>
para3<br>
</body>
</html>
答案 2 :(得分:0)
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="utf-8" indent="yes" />
<xsl:template match="/section">
<html>
<body>
<xsl:for-each select="para/text()">
<xsl:value-of select="."/>
<br/>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>