powershell - 使用Powershell编辑多个XML文件

标签 powershell powershell-1.0

如何从指定目录中获取多个XML文件的列表,并使用Powershell为每个文件在第二个根节点下添加一个元素?

例子:
我想在FIRST <LastName>SomeName</LastName>元素内添加<Names>:

<People>
  <Names>
      <FirstName>someFirstName</FirstName>
  </Names>
  <Names>
      <FirstName>myFirstName</FirstName>
      <Address>SomeAddress</Address>
  </Names>
</People>

会变成:
<People>
  <Names>
      <LastName>SomeName</LastName>
      <FirstName>someFirstName</FirstName>
  </Names>
  <Names>
      <FirstName>myFirstName</FirstName>
      <Address>SomeAddress</Address>
  </Names>
</People>

最佳答案

您可以使用CreateElementAppendChild方法进行操作

Get-ChildItem c:\temp\ *.xml | 
    % { 
        $xml      = [xml](Get-Content $_.fullname)
        $lastName = $xml.CreateElement('LastName')
        $lastName.PsBase.InnerText = 'SomeName'
        $null     = $xml.People.Names[0].AppendChild($lastName)
        $xml.Save($_.FullName)
    }

如果您运行PowerShell V2,则无需使用PsBase属性:
        $lastName.InnerText = 'SomeName'

当然还有其他方法,但这是很容易的一种方法。

如果该节点在xml中更深,则可以使用Xpath这样的方法(都找到第一个Names节点):
$node = (Select-Xml -Xml $x -XPath '//Names[1]').Node
$node = (Select-Xml -Xml $x -XPath '//Names[position()=1]').Node

关于powershell - 使用Powershell编辑多个XML文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324882/

相关文章:

xml - 带有 XPath 和多个命名空间的 SelectSingleNode

powershell - Powershell和“取消”按钮或ESC

json - 如何将 JSON(字符串数据)传递给 PowerShell?

.net - 将 PowerShell 与 .NET 3.5 运行时/库一起使用

powershell - Powershell和Plink-如何捕获消息 “Access Denied”

datetime - 文件日期元数据无法正确显示

powershell - Out-Gridview 去除下划线

powershell - 如何在发生某些外部事件之前暂停 Powershell 脚本?

powershell - Copy-Item 将目录及其内容复制到 UNC 路径

regex - 如何匹配脚本链接?