Clearing out xdt element if it has no children

2019-06-19 23:18发布

问题:

So I'm starting to play with nuget and it's web.config install/uninstall.xdt values.

My question would be, Is there and xdt:Transform that will clear out empty elements. I didn't find anything here. https://msdn.microsoft.com/en-us/library/dd465326%28v=vs.110%29.aspx

Here's my example.

My current Web.config.install.xdt looks like this

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <compilation xdt:Transform="InsertIfMissing">
      <assemblies xdt:Transform="InsertIfMissing">
        <add xdt:Transform="InsertIfMissing" xdt:Locator="Match(assembly)" assembly="MyAssembly, Version=4.5.4.0, Culture=neutral, PublicKeyToken=asdfasdfasdfasdf" />
      </assemblies>
    </compilation>
  </system.web>
</configuration>

and my uninstall looks like this

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <compilation>
      <assemblies>
        <add xdt:Transform="Remove" xdt:Locator="Match(assembly)" assembly="MyAssembly, Version=4.5.4.0, Culture=neutral, PublicKeyToken=asdfasdfasdfasdf" />
      </assemblies>
    </compilation>
  </system.web>
</configuration>

Here's my web.config before (simplified)

  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>

Here's my web.config after the install.xtd

  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="MyAssembly, Version=4.5.4.0, Culture=neutral, PublicKeyToken=asdfasdfasdfasdf" />
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5" />
  </system.web>

Here's my web.config after the uninstall

  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5" />
  </system.web>

Is there anyway to get rid of the tag?

回答1:

It appears you can specify multiple transformations on an element. Therefore you could remove the content from your install and then check if the element has children, if not remove the element.

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <compilation>
      <assemblies>
        <add xdt:Transform="Remove" xdt:Locator="Match(assembly)" assembly="MyAssembly, Version=4.5.4.0, Culture=neutral, PublicKeyToken=asdfasdfasdfasdf" />
      </assemblies>
      <assemblies xdt:Locator="Condition(count(*) = 0)" xdt:Transform="Remove"/>
    </compilation>
  </system.web>
</configuration>