通过命令行修改XML

时间:2011-03-09 10:04:52

标签: .net xml command-line linq-to-xml xslt

我正在寻找一种更好的方法来修补XML(实际上是app.config文件)。更具体地说,我需要向<appConfig>部分(可能不存在)以及匹配条目的多个<bindingRedirect>元素添加内容。

我还需要将其作为命令行工具,以便于部署。

我想过以几种方式解决这个问题:

  1. 使用LINQ to XML修补文件的临时控制台应用程序 - 最简单
  2. 使用XSLT - 保存修改后的XML的副本,稍后替换原始版本(除非可以就地转换源XML吗?)
  3. 使用XML Diff and Patch,但似乎生成的diffgram引用了精确的节点位置,例如<xd:node match="1">等。
  4. ad-hoc解决方案是最简单的,但我觉得它有点作弊。我不太了解XSLT,但这听起来像是最好的解决方案......

    在您看来,什么是“工作的最佳工具?”

3 个答案:

答案 0 :(得分:4)

如果使用Xslt是一个选项,您可以使用MSBuild在命令行上驱动转换。

配置文件app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
              <assemblyIdentity name="myAssembly" publicKeyToken="32ab4ba45e0a69a1" culture="neutral" />
              <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
          </dependentAssembly>
      </assemblyBinding>
   </runtime>
</configuration>

Xslt appconfig.xslt

此示例xslt将复制源app.config中的所有内容,并添加<appSetting />节点(如果该节点不存在):

<?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="/">
        <xsl:apply-templates />
    </xsl:template>

    <xsl:template match="configuration">
        <xsl:element name="configuration">
            <xsl:if test="self::node()[not(appSettings)]">
                <xsl:element name="appSettings" />
            </xsl:if>
            <xsl:apply-templates />
        </xsl:element>
    </xsl:template>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

MSBuild脚本appconfig.proj

此示例MSBuild项目脚本将复制/备份源 app.config 并使用给定的xslt样式表对其进行转换。

<Project ToolsVersion="4.0" DefaultTargets="Transform" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <ItemGroup>
        <AppConfigFile Include="app.config" />
    </ItemGroup>

    <Target Name="Clone">
        <Copy SourceFiles="@(AppConfigFile)" DestinationFiles="clone.config">
            <Output TaskParameter="CopiedFiles" ItemName="ClonedConfig" />
        </Copy>
     </Target>

     <Target Name="Transform" DependsOnTargets="Clone">
         <XslTransformation XslInputPath="appconfig.xslt" XmlInputPaths="@(ClonedConfig)" OutputPaths="app.config" />
     </Target>
</Project>

从命令行运行

<path to .NET framework 4>\MSBuild.exe appconfig.proj

答案 1 :(得分:4)

您可以为Microsoft XSLT处理器使用以下XSLT命令行实用程序:

  1. msxsl.exe (已经存在了将近10年)。使用MSXML执行转换(可以指定不同的版本)。

  2. Oleg Tkachenko's nxslt.exe XslCompiledTransform的命令行工具 - 这是 Mvp.Xml 项目的一部分。

答案 2 :(得分:3)

根据我使用XSLT的经验可能会有效,但请记住,您也希望保留它。有一个很好的工具可用于构建xslt visual,名为MapForce,我过去曾使用它可能会有所帮助。

最近在工作中我需要做一个类似的任务 - 将XML文件从格式A转换为格式B - 使用Linq是最快捷,最简单的原因,目前也很容易维护。

所以我的建议是做最简单的工作并快速解决,除非你从使用XSLT中获得明显的好处。

相关问题