[英]Removing related elements using XSLT 1.0
我正在嘗試從下面的XML中刪除具有File子節點且擴展名為“ config”的Component元素。 我已經設法完成了這一部分,但是我還需要刪除與這些Components具有相同“ Id”值的匹配ComponentRef元素。
<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" />
</ComponentGroup>
</Fragment>
基於其他SO答案,我提出了以下XSLT來刪除這些Component元素:
<?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>
不幸的是,這不會刪除匹配的ComponentRef元素(即具有相同“ Id”值的元素)。 XSLT將刪除ID為“ Comp1”的組件,但不會刪除ID為“ Comp1”的ComponentRef。 如何使用XSLT 1.0做到這一點?
一種相當有效的方法是使用xsl:key
來識別配置組件的ID:
<?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>
這個怎么樣? 我還對您的原始文件做了一些小的更改以簡化操作(檢查@source屬性是否以'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>
它具有一個模板,該模板與具有與上一個模板匹配的Component具有相同Id屬性的ComponentRef匹配。 一件事-' //Component
'效率不高。 您應該可以用效率更高的東西代替它-我不知道您的XML結構
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.