从命令行更新XML

我有几个应用程序以XML格式存储他们的configuration文件。 对于一个普通的应用程序,使用基于文本的configuration,我可以使用perl,sed或awk或者百万个工具中的任何一个来轻松更新一个值。 我正在寻找类似于XML的东西,这将允许我轻松可靠地执行操作,如更新值,添加节点或删除节点。

常规的文本parsing看起来太冒险了,因为我对物理文件格式没有真正的保证。

MS Powershell中的XMLparsing比我在其他任何语言或环境中见过的任何parsing机制都要容易。

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

<root> <one>I like applesauce</one> <two>You sure bet I do!</two> </root> 

您可以轻松地从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") 

文件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> 

难以置信的容易! 请享用。

Powershell是微软在Windows Server 2008和Windows 7中提供的新shell,可以免费下载XP / Vista / Server 2003(也许是其他版本)。

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

如果我正确理解这个问题,您正在寻找一个类似于XML的不同的configuration文件存储格式。 XML的最大优点之一就是它为您提供了一个结构化的数据格式。 如果您违反了DTD或“模板”,则您的XMLconfiguration文件格式不正确。 在过去的一些我自己的开发工作,脚本,程序和应用程序,我曾经使用INI格式的文件。 虽然INI的很容易parsing,并且可以支持类似的添加,删除,更新,我喜欢XML B / C它是:

  1. 广泛使用
  2. 用Perl的XML :: LibXML轻松parsing
  3. 比INI文件提供更大的灵活性
  4. 最好的解决scheme坚持严格的格式和程序结构