xml - 匹配可能是根的节点
问题描述
我需要匹配 xslt 中可能是根元素或可能是根元素的子元素的节点。那可能吗?
这是一个示例文件,我需要在其中匹配Package
根元素。
<Package>
<Target>Tablet</Target>
<Type>DeviceApp</Type>
<Name>MyName</Name>
<Version>1.2.3</Version>
<Description>My Description</Description>
<UnneededElmt></UnneededElmt>
</Package>
<!-- Expected result: -->
<Target>Tablet</Target>
<Type>DeviceApp</Type>
<Name>MyName</Name>
<Version>1.2.3</Version>
<Description>My Description</Description>
这是另一个示例,我需要Package
在子级别匹配元素。
<testcase-root>
<Package>
<Target>Tablet</Target>
<Type>DeviceApp</Type>
<Name>MyName</Name>
<Version>1.2.3</Version>
<Description>My Description</Description>
<UnneededElmt></UnneededElmt>
</Package>
</testcase-root>
<!-- Expected result: -->
<testcase-root>
<Target>Tablet</Target>
<Type>DeviceApp</Type>
<Name>MyName</Name>
<Version>1.2.3</Version>
<Description>My Description</Description>
</testcase-root>
对于第一种情况,这种转换可以满足我的需要:
<xsl:template match="/" >
<xsl:copy-of select="//Package/*[not(self::UnneededElmt)]"/>
</xsl:template>
对于第二个,它适用于<xsl:template match="//Package" >
. 但我需要一个涵盖这两种情况的匹配项(或明确的“不,不可能”:))。
解决方案
试试这种方式:
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"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Package">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="UnneededElmt"/>
</xsl:stylesheet>
推荐阅读
- ckeditor - 在 ckeditor 封面中最大化保存在数据输入屏幕上
- c# - Asp.net Core 的 POST 方法将 DateTime.Now 转换为模型绑定上的 Min Date
- c# - 从 UTF16le 转换为 UTF8
- reactjs - Webpack 运行调试器?
- c# - 从 Azure AppService 返回自身的 GET 请求返回 502 Bad Gateway 错误
- html - 在没有jQuery的表格行末尾附加一个元素?(使用 AngularJS)
- c# - 如何以编程方式将按钮控件组织到网格中?
- selenium - Selenium UI 自动化测试的代码覆盖率工具
- php - 在 MacOS 上安装 Apache、PHP、MySql 和 phpMyAdmin
- grpc - gRPC 连接:使用 keepAlive 还是 idleTimeout?