如何在XSLT中进行部分转换

时间:2018-10-13 09:55:09

标签: xml xslt xslt-1.0

我已经在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>

预期结果:

enter image description here

1 个答案:

答案 0 :(得分:2)

只需从身份转换模板开始,然后为包含tr个子元素的元素添加一个模板,即可将它们包装在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>

https://xsltfiddle.liberty-development.net/6qVRKwV