首页 > 解决方案 > 我将如何使用 XSLT 转换此 XML?

问题描述

给定以下 XML 文档:

<?xml version="1.0" encoding="utf-8"?>
<Store>
  <Location>
    <State>WA</State>
  </Location>
  <Transaction>
    <Category>Fruit</Category>
  </Transaction>
  <Customer>
    <Category>Rewards</Category>
  </Customer>
  <Document>
  <!-- Huge XML blob here -->
  </Document>
</Store>

我将如何编写 XSLT(版本 1 或 2)将其转换为以下 XML 文档:

<?xml version="1.0" encoding="utf-8"?>
<Transaction>
  <Account>
    <Type>Rewards</Type>
  </Account>
  <Type>
    <Department>Fruit</Department>
  </Type>
  <Document>
    <!-- Huge XML blob here -->
  </Document>
</Transaction>

?

基本上,我需要重新排列/重命名一些元素,删除一些元素,并复制一些元素,就像它们出现在原始元素中一样。

标签: xmlxslt

解决方案


您可以使用以下 XSLT-1.0 样式表/模板来实现您的目标:

<xsl:stylesheet version = "1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
 <xsl:output method="xml" indent="yes" />

<xsl:template match="Store">
    <Transaction>
        <Account>                            <!-- The Store/Customer/Category is moved to Transaction/Account/Type. -->
            <Type>
                <xsl:value-of select="Customer/Category" />
            </Type>
        </Account>
        <Type>                               <!-- The Store/Transaction/Fruit element is moved/renamed to Transaction/Type/Department. -->
            <Department>
                <xsl:value-of select="Transaction/Category" />
            </Department>
        </Type>
        <product>Rasberries</product>        <!-- Adding a new element with a constant value -->
        <xsl:copy-of select="Document" />    <!-- The Store/Document element is copied along with all of its sub elements unchanged into the result as the Transaction/Document element. -->
    </Transaction>
</xsl:template>

</xsl:stylesheet>

Store/Location/State 元素值被删除。

这是通过不提及它来完成的。


推荐阅读