[英]Modifying an XML via command line
我正在寻找一种更好的方法来修补XML(实际上是app.config
文件)。 更具体地说,我需要在<appConfig>
部分(可能不存在)中添加一些内容,并将几个<bindingRedirect>
元素添加到匹配的条目中。
我还需要它作为命令行工具,以便于部署。
我想过以几种方式解决这个问题:
<xd:node match="1">
等。 ad-hoc解决方案是最简单的,但我觉得它有点作弊。 我不太了解XSLT,但这听起来像是最好的解决方案......
在您看来,什么是“工作的最佳工具?”
如果使用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
您可以为Microsoft XSLT处理器使用以下XSLT命令行实用程序:
msxsl.exe (已存在近10年)。 使用MSXML执行转换(可以指定不同的版本)。
Oleg Tkachenko的 XslCompiledTransform 的nxslt.exe命令行实用程序 - 这是Mvp.Xml项目的一部分。
根据我的经验,使用XSLT可能会有效,但请记住,您也希望保持它。 有一个很好的工具来构建我曾经使用过的可能有用的xslt视觉MapForce 。
最近在工作中我需要做一个类似的任务 - 将XML文件从格式A转换为格式B - 使用Linq是最快捷,最简单的原因,目前也很容易维护。
所以我的建议是做最简单的工作并快速解决,除非你从使用XSLT中获得明显的好处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.