xml - XSLT 缺少的元素并未全部添加
问题描述
我的 XSLT 没有添加所有缺失的元素。我需要把这些领域和
这是我正在使用的 XML。
<Report>
<Table>
<ID>4</ID>
<Name>R2D2</Name>
</Table>
<Table>
<ID>0</ID>
<Name>T1000</Name>
</Table>
</Report>
这是 XSLT。(如果可能,我想使用 XSLT 2 或 3)
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="node()">
<xsl:copy>
<xsl:apply-templates select="node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Table[not(Address)]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<Address/>
</xsl:copy>
</xsl:template>
<xsl:template match="Table[not(City)]">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
<City/>
</xsl:copy>
</xsl:stylesheet>
由于某种原因地址丢失,我得到了这个结果!
<Report>
<Table>
<ID>4</ID>
<Name>RD2</Name>
<City/>
</Table>
<Table>
<ID>0</ID>
<Name>ZZZZ</Name>
<City/>
</Table>
</Report>
我期待得到这样的结果。此处如果地址和城市缺失,则包括在内。
<Report>
<Table>
<ID>4</ID>
<Name>RD2</Name>
<Address/>
<City/>
</Table>
<Table>
<ID>0</ID>
<Name>ZZZZ</Name>
<Address/>
<City/>
</Table>
</Report>
解决方案
由于某种原因,地址丢失!
地址丢失,因为没有地址和城市的表格与您的所有三个模板匹配,其中两个具有相同的优先级 - 仅应用了最后一个 - 请参阅:https ://www.w3.org/ TR/xslt20/#冲突
这是您可以解决此问题的一种方法:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Table[not(Address and City)]">
<xsl:copy>
<xsl:apply-templates/>
<xsl:if test="not(Address)">
<Address/>
</xsl:if>
<xsl:if test="not(City)">
<City/>
</xsl:if>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- css - 无法在css中加载背景图像
- java - 无法使用唯一键从 Firebase 检索用户位置数据
- jenkins - 詹金斯管道 - 这个功能来自哪里
- mysql - SQL:将列值链接到列名以满足某些条件
- apache-kafka - KafkaConsumer 未能“重新订阅”
- python - 在尚未开始计算的情况下持续存在内存延迟
- postgresql - Sqoop 从 Postgre 到 Hive 并转换为 ORC 格式
- react-native - 反应本机查看 PDF
- node.js - 如何通过nodejs更新mongoDB中的嵌套对象文档?
- pdf - Nitro PDF:向 PDF 页面添加文本。在 Adobe Acrobat Reader DC 中打开时,它显示为注释