Removing related elements using XSLT 1.0
I'm attempting to remove Component elements from the XML below that have File children with the extension "config." I've managed to do this part, but I also need to remove the matching ComponentRef elements that have the same "Id" values as these Components.
<Fragment>
<DirectoryRef Id="MyWebsite">
<Component Id="Comp1">
<File Source="Web.config" />
</Component>
<Component Id="Comp2">
<File Source="Default.aspx" />
</Component>
</DirectoryRef>
</Fragment>
<Fragment>
<ComponentGroup Id="MyWebsite">
<ComponentRef Id="Comp1" />
<ComponentRef Id="Comp2" />
<开发者_如何学JAVA;/ComponentGroup>
</Fragment>
Based on other SO answers, I've come up with the following XSLT to remove these Component elements:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="Component[File[substring(@Source, string-length(@Source)- string-length('config') + 1) = 'config']]" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Unfortunately, this doesn't remove the matching ComponentRef elements (i.e. those that have the same "Id" values). The XSLT will remove the component with the Id "Comp1" but not the ComponentRef with Id "Comp1". How do I achieve this using XSLT 1.0?
A fairly efficient approach is to use xsl:key
to identify the IDs of config components:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:key name="configComponent"
match="Component[File/@Source[substring(.,
string-length() - string-length('config') + 1) = 'config']]"
use="@Id" />
<xsl:template match="Component[key('configComponent', @Id)]" />
<xsl:template match="ComponentRef[key('configComponent', @Id)]" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
How about this? I've made a small change to your original to simplify things as well (it's simpler to check if the @source attribute ends with 'config').
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="Component[substring(@Source, string-length(@Source) - 5) = 'config']" />
<xsl:template match="ComponentRef[//Component[substring(@Source, string-length(@Source) - 5) = 'config']/@Id = @Id]"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
This has a template that matches any ComponentRef that has the same Id attribute as a Component matched by the preceding template. One thing - the '//Component
' is not efficient. You should be able to replace that with something more efficient - I don't know your XML structure
精彩评论