问题
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>
回答1:
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>
来源:https://stackoverflow.com/questions/17950377/delete-node-from-xml-using-xslt-based-on-node-value