如何使用XSLT从XML文件删除节点或标签

时间:2018-07-06 07:07:15

标签: xml xslt

我的XSl为

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:fn="http://www.w3.org/2005/xpath-functions" xmlns:cdm="http://www.businessneed.com/cdm"   
    exclude-result-prefixes="fn cdm xs">
    <xsl:output method="xml" version="1.0" encoding="UTF-8"
        indent="yes" omit-xml-declaration="yes" exclude-result-prefixes="cdm" />
<xsl:template match="cdm:attributeList">
        <attributeList>     
        <xsl:apply-templates select="cdm:attribute" />  
</xsl:stylesheet>

我的结果XML为

<attributeList>
             <attribute id="1680231133">
                   <attributeCode>FirstName</attributeCode>
                   <attributeValue>Vishal</attributeValue>
              </attribute>

            <attribute id="1680231134">
                   <attributeCode>LastName</attributeCode>
                   <attributeValue>Patil</attributeValue>
              </attribute>
            </attributeList>

我要删除

<attribute id="1680231133">
           <attributeCode>FirstName</attributeCode>
           <attributeValue>Vishal</attributeValue>
      </attribute>

所以我的结果只会是

 <attributeList>    
    <attribute id="1680231134">
           <attributeCode>LastName</attributeCode>
           <attributeValue>Patil</attributeValue>
      </attribute>
    </attributeList>

我已经尝试过:-

<xsl:template match="@* | node()">
                        <xsl:copy>
                            <xsl:apply-templates select="@* | node()"/>
                        </xsl:copy>
                </xsl:template>                 
             <xsl:template match="cdm:attributeList/cdm:attribute/attributeCode/Firstname"/>

但无法工作

如何使用XSL语法实现此目标 预先感谢

2 个答案:

答案 0 :(得分:0)

尝试使用下面的XSLT。

它使用identity transform模板将输入原样复制到输出,然后使用另一个模板删除所有具有attribute的{​​{1}}元素。

attributeCode = 'FirstName'

输出

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" />
    <xsl:strip-space elements="*" />

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="attribute[attributeCode = 'FirstName']" />
</xsl:stylesheet>

答案 1 :(得分:0)

<xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()" />
        </xsl:copy>
    </xsl:template>

 <xsl:template match="cdm:attributeList/cdm:attribute[cdm:attributeCode = 'FirstName']"/>

我忘记将名称空间前缀放在变量“ attributeCode”之前