我有以下.NET 4.7应用程序的简化app.config文件:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
<runtime>
</runtime>
</configuration>
现在,我需要在其中插入一个名为Dependencies
的新节(元素(,如果该节还不存在的话。该部分需要有一个名为MyDependencies
的子元素,它可以包含几个CustomDependency
元素。这里有一个例子:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
<Dependencies>
<MyDependencies>
<CustomDependency Name="UniqueName" Id="12345678-1234-1234-1234-123456781234" AnotherAttribute="CustomValue"/>
</MyDependencies>
</Dependencies>
<runtime>
</runtime>
</configuration>
但是,如果具有特定名称的CustomDependency
元素已经存在,则只需要更改该元素的属性值(Id
和AnotherAttribute
(。这应该通过使用提交到XSLT文件的参数来完成。
因此,输入可能看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
<Dependencies>
<MyDependencies>
<CustomDependency Name="UniqueName" Id="ABC45678-1234-1234-1234-123456781234" AnotherAttribute="WrongValue"/>
<CustomDependency Name="UniqueName2" Id="87654321-1234-1234-1234-123456781234" AnotherAttribute="CustomValue2"/>
</MyDependencies>
<YourDependencies>
<CustomDependency Name="UniqueName2" Id="ABC54321-1234-1234-1234-123456781234" AnotherAttribute="CustomValue2"/>
</YourDependencies>
</Dependencies>
<runtime>
</runtime>
</configuration>
在这种情况下,名称为UniqueName
的元素的属性值,例如
<CustomDependency Name="UniqueName" Id="ABC45678-1234-1234-1234-123456781234" AnotherAttribute="WrongValue"/>
必须更新为
<CustomDependency Name="UniqueName" Id="12345678-1234-1234-1234-123456781234" AnotherAttribute="CustomValue"/>
实现这一点需要XSLT代码的外观如何?
试试这个:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />
<xsl:template match="@*|node()" name="copy-all">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="/configuration/Dependencies/MyDependencies/CustomDependency[@Name='UniqueName']/@Id">
<xsl:attribute name="Id">CustomValue</xsl:attribute>
</xsl:template>
<xsl:template match="/configuration/Dependencies/MyDependencies/CustomDependency[@Name='UniqueName']/@AnotherAttribute">
<xsl:attribute name="AnotherAttribute">CustomValue</xsl:attribute>
</xsl:template>
<xsl:template match="startup[not(../Dependencies)]">
<xsl:call-template name="copy-all" />
<xsl:element name="Dependencies">
<xsl:element name="MyDependencies">
<xsl:element name="CustomDependency">
<xsl:attribute name="Name">UniqueName</xsl:attribute>
<xsl:attribute name="Id">12345678-1234-1234-1234-123456781234</xsl:attribute>
<xsl:attribute name="AnotherAttribute">CustomValue</xsl:attribute>
</xsl:element>
</xsl:element>
</xsl:element>
</xsl:template>
</xsl:stylesheet>