【问题标题】:How would I transform this XML using XSLT?我将如何使用 XSLT 转换此 XML?
【发布时间】:2018-07-24 17:57:12
【问题描述】:

给定以下 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>

?

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

  • Store/Location/State 元素值被删除。
  • Store/Transaction/Fruit 元素已移动/重命名为 Transaction/Type/Department。
  • Store/Customer/Category 移至 Transaction/Account/Type。
  • Store/Document 元素连同其所有未更改的子元素一起复制到作为 Transaction/Document 元素的结果中。

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    您可以使用以下 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 元素值被删除。

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

    【讨论】:

    • 谢谢@zx485。如果我想在结果中添加一个新元素,比如说一个 元素,其值被硬编码为“Rasberries”。
    • 你帮了大忙。你能看看我的新问题吗? stackoverflow.com/questions/51519950/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2019-05-30
    • 2021-12-22
    • 2016-08-24
    • 1970-01-01
    • 2012-10-12
    • 2021-07-22
    相关资源
    最近更新 更多