xml - 删除满足条件的节点,如果为空则删除父节点
问题描述
我正在尝试删除所有满足条件的元素节点,然后删除父节点(如果它仍然没有子节点)。
我成功删除了所有满足我条件的孩子,但不知道如何删除父母如果它仍然是空的。
<root>
<parent>
<childA>
<grandchildX>03</grandchildX>
<grandchildY>02</grandchildY>
</childA>
</parent>
</root>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="childA[grandchildX[text()='03']][grandchildY[text()='02']]"/>
</xsl:stylesheet>
XSLT 样式表必须<parent>
在它有其他子项时输出<childA>
(例如<childB>
)(这已经有效)。
解决方案
使用 XSLT 3(并假设xsl:strip-space
),您可以xsl:where-populated
在模板中使用parent
:
<xsl:template match="parent">
<xsl:where-populated>
<xsl:next-match/>
</xsl:where-populated>
</xsl:template>
完整的样式表将是
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all"
version="3.0">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:mode on-no-match="shallow-copy"/>
<xsl:template match="childA[grandchildX[text()='03']][grandchildY[text()='02']]"/>
<xsl:template match="parent">
<xsl:where-populated>
<xsl:next-match/>
</xsl:where-populated>
</xsl:template>
</xsl:stylesheet>
在https://xsltfiddle.liberty-development.net/ej9EGdh上使用 Saxon 9.8 HE 的在线示例。
对于 XSLT 1,我认为您可以尝试使用空模板
<xsl:template match="parent[childA[grandchildX[. = '03']][grandchildY[. ='02']] and not(*[not(self::childA[grandchildX[. = '03']][grandchildY[. ='02']])])]"/>
即完整的代码是
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="childA[grandchildX[. = '03']][grandchildY[. ='02']]"/>
<xsl:template match="parent[childA[grandchildX[. = '03']][grandchildY[. ='02']] and not(*[not(self::childA[grandchildX[. = '03']][grandchildY[. ='02']])])]"/>
</xsl:stylesheet>
推荐阅读
- python - 从 Pandas 的日期范围创建随机排序的日期
- android - 使用 Python3 从设备发送照片并通过 TCP 在 Android 设备上接收照片会在 Android 设备上产生 OOM
- python - 使用 matplotlib 沿图表绘制表格
- php - 将 laravel 项目部署到 Azure 时出现 SQL SSL 错误
- node.js - 如何在 Nodejs 中使用 Twilio API 在会议开始时添加“说”消息
- python - 摄像机不会随 cv2.VideoCapture(0).release() 转动
- java - String 类的 split 方法和每个循环都没有给出所需的输出
- python - 枕头旋转正在失去 Alpha 值
- python - TensorFlow 模型训练
- javascript - 自动滚动项目列表