xml - 我将如何使用 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>
?
基本上,我需要重新排列/重命名一些元素,删除一些元素,并复制一些元素,就像它们出现在原始元素中一样。
- Store/Location/State 元素值被删除。
- Store/Transaction/Fruit 元素被移动/重命名为 Transaction/Type/Department。
- Store/Customer/Category 移动到 Transaction/Account/Type。
- Store/Document 元素连同其所有未更改的子元素一起复制到作为 Transaction/Document 元素的结果中。
解决方案
您可以使用以下 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 元素值被删除。
这是通过不提及它来完成的。
推荐阅读
- algorithm - 动态规划 2 个城市搬运工的最大利润
- gremlin - 更新 gremlin-server 后的问题
- python - Numpy 数组追加更改其 dtype
- python - 尝试调整窗口大小时,Tkinter 和 cv2 冻结
- ios - Swift 数据转换为 UInt64
- dictionary - SWIFTUI 调用密钥字典不适用于错误:“密钥路径中的“() -> Bool”类型的下标索引必须是可散列的”
- docker - docker-compose 在 Ubuntu WSL 2 上找不到环境变量 $PWD
- javascript - 在 Rock Paper Scissors - Java Script 中显示相同的结果
- c++ - 子对象、包含对象、成员对象:差异?
- javascript - 更新未捕获且无法更新输入字段