如何使用 PowerShell/XPath 更改 XML 并保存文档? [英] How do I alter XML with PowerShell/XPath and save the document?

查看:53
本文介绍了如何使用 PowerShell/XPath 更改 XML 并保存文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 PowerShell 来更改 XML.我无法使用 XPath 复制 XML.我可以加载 XML,但我不知道如何使用 XPath 列出 XML 并使用我检索的内容创建另一个 XML 文件.

I'm looking to use PowerShell to alter XML. I haven't been able to copy XML using XPath. I can load the XML, but I can't figure out how to list the XML with an XPath and create another XML file with what I retrieve.

$doc = new-object "System.Xml.XmlDocument"
$doc.Load("XmlPath.xml")

另外,您如何将删除的 XML 添加到另一个 XML 文件中?

Also, how would you add the removed XML to another XML file?

推荐答案

如果您使用的是 PowerShell 2.0,您可以使用新的 Select-Xml cmdlet 根据 XPath 表达式选择 xml,例如:

If you're using PowerShell 2.0 you can use the new Select-Xml cmdlet to select xml based on an XPath expression e.g.:

$xml = '<doc><books><book title="foo"/></books></doc>'
$xml | Select-Xml '//book'
Node    Path          Pattern
----    ----          -------
book    InputStream   //book

删除节点:

PS> $xml =[xml]'<doc><books><book title="foo"/><book title="bar"/></books></doc>'
PS> $xml | Select-Xml -XPath '//book' | 
        Foreach {$_.Node.ParentNode.RemoveChild($_.Node)}

title
-----
foo
bar

PS> $xml.OuterXml
<doc><books></books></doc>

然后保存到文件:

$xml.Save("$pwd\foo.xml")
Get-Content foo.xml
<doc>
  <books>
  </books>
</doc>

这篇关于如何使用 PowerShell/XPath 更改 XML 并保存文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆