xml - 如何在 XSLT 中进行部分转换
问题描述
我已经对 XML 进行了 XSLT 转换,现在想应用 XSLT 来更改一些内容。
如何将所有tr元素包装在table元素中?我在 C# 中使用 XSLT 1.0。
XML
<?xml version="1.0" ?>
<div class="group">
<div class="group-header">A</div>
<div class="group-body">
<div class="group">
<div class="group-header">B</div>
<div class="group-body">
<div class="group">
<div class="group-header">C</div>
<div class="group-body">
<tr>C1</tr>
<tr>C2</tr>
<tr>C3</tr>
</div>
</div>
<div class="group">
<div class="group-header">D</div>
<div class="group-body">
<tr>D1</tr>
<tr>D2</tr>
<tr>D3</tr>
</div>
</div>
</div>
</div>
</div>
</div>
预期结果:
解决方案
只需从身份转换模板开始,然后为包含tr
子元素的元素添加一个模板,以将它们包装在 a 中table
:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="*[not(self::table) and tr]">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<table>
<xsl:apply-templates/>
</table>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>