Delete node from xml using xslt based on node valu

2019-07-25 04:53发布

I am trying to work on this XML file where i would like to delete all the matching nodes based on the latest node value. In the following example the latest node value is "${DELETE}" Latest node value will be always "${DELETE}" and the node will be always at the bottom of an XML file.

Example:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<projects>
        <project id="properties1">
            <property name="prop1">some-value</property>       
            <property name="prop2">abc</property>               
            <property name="prop3">def</property>       
         </project>
        <project id="properties2">
            <property name="prop">testing prop from pom.xml</property>
            <property name="prop1">${DELETE}</property> 
            <property name="prop4">abc</property>       
            <property name="prop5">xyz</property>   
        </project>
</projects>

Expected Output is:

<projects>
        <project id="properties1">     
            <property name="prop2">abc</property>               
            <property name="prop3">def</property>       
         </project>
        <project id="properties2">
            <property name="prop">testing prop from pom.xml</property>
            <property name="prop4">abc</property>       
            <property name="prop5">xyz</property>   
        </project>
</projects>

标签: xml xslt
1条回答
Anthone
2楼-- · 2019-07-25 05:29

With XSLT 2.0 and an XSLT 2.0 processor you could use

<xsl:stylesheet version="2.0" exclude-result-prefixes="xs"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xsl:key name="prop" match="property" use="@name"/>

    <xsl:variable name="prop-to-delete" select="/projects/project[last()]/property[. = '${DELETE}']/@name"/>

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

    <xsl:template match="key('prop', $prop-to-delete)"/>

</xsl:stylesheet>

With XSLT 1.0 you can't use a variable reference or path as the key argument in a match pattern so there you have to spell out the condition:

<xsl:stylesheet version="1.0" exclude-result-prefixes="xs"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

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

    <xsl:template match="property[@name = /projects/project[last()]/property[. = '${DELETE}']/@name]"/>

</xsl:stylesheet>
查看更多
登录 后发表回答