首页 > 解决方案 > 匹配可能是根的节点

问题描述

我需要匹配 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" >. 但我需要一个涵盖这两种情况的匹配项(或明确的“不,不可能”:))。

标签: xmlxsltxpath

解决方案


试试这种方式:

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>

推荐阅读