从命令行更新 XML [windows]

Mik*_*age 5 windows command-line-interface xml

我有一些应用程序以 XML 格式存储它们的配置文件。对于常规应用程序,使用基于文本的配置,我可以通过使用 perl、sed、awk 或一百万种工具中的任何一种来轻松更新值。我正在为 XML 寻找类似的东西,这将使我能够轻松可靠地执行操作,例如:更新值、添加节点或删除一个值。

常规文本解析似乎风险太大,因为我对物理文件格式没有真正的保证。

小智 10

MS Powershell 中的 XML 解析比我在我个人遇到的任何其他语言或环境中看到的任何解析机制都容易。

给定一些 XML 文件(test.xml):

<root>
  <one>I like applesauce</one>
  <two>You sure bet I do!</two>
</root>
Run Code Online (Sandbox Code Playgroud)

您可以从 Powershell 中轻松访问、修改和附加 XML 文件的节点、值和属性。

# load XML file into local variable and cast as XML type.
$doc = [xml](Get-Content ./test.xml)

$doc.root.one                                   #echoes "I like applesauce"
$doc.root.one = "Who doesn't like applesauce?"  #replace inner text of <one> node

# create new node...
$newNode = $doc.CreateElement("three")
$newNode.set_InnerText("And don't you forget it!")

# ...and position it in the hierarchy
$doc.root.AppendChild($newNode)

# write results to disk
$doc.save("./testNew.xml")
Run Code Online (Sandbox Code Playgroud)

文件 testNew.xml 中的结果 XML:

<root>
  <one>Who doesn't like applesauce?</one>
  <two>You sure bet I do!</two>
  <three>And don't you forget it!</three>
</root>
Run Code Online (Sandbox Code Playgroud)

难以置信的容易!享受。

Powershell 是 Microsoft 的新外壳,随 Windows Server 2008 和 Windows 7 一起提供,可免费下载用于 XP/Vista/Server 2003(可能还有其他)。

一些有用的链接:
从其他来源生成 XML
向 XML 添加元素:
示例 1,MSDN PowerShell 博客
示例 2,PC-Pro(英国)