使用 Powershell 添加和删除 Xmlnode [英] Adding and Removing Xmlnode using Powershell

查看:65
本文介绍了使用 Powershell 添加和删除 Xmlnode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从多个 xml 文件中添加和删除元素.我遇到了两个问题.它自动删除了空元素,其次它没有删除我想要的内容

I am trying to add and remove elements from multiple xml files. i ran into two issue. it removed empty elements automatically and second it did not remove what i wanted to

我有这样的 xml

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>
         <itemToRemove>true</itemToRemove>
         <emptyItem/>
         <otheritem>1</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
   </App>
</Entity>

我想要的是

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>

         <emptyItem/>
         <otheritem>1</otheritem>
      </person>
      <person>

         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <person>

         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <newItemtoAdd>2001-01-01</newItemtoAdd>
   </App>
</Entity>

我在上面的输出 xml 中添加了 newItemtoAdd 元素并删除了 itemToRemove.

with the current script i have used what i get is this

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>
         <itemToRemove>true</itemToRemove>
         <otheritem>1</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <otheritem>3</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <otheritem>3</otheritem>
      </person>
      <newItemtoAdd>2001-01-01</newItemtoAdd>
   </App>
</Entity>

emptyItem 节点被删除,我不想发生,添加 newItemtoAdd 这很好,itemToRemove 节点没有被删除,这不是我想要的

这是我的脚本

Get-ChildItem D:\Projects\*.xml | 
    % { 
        [xml]$xml      = [xml](Get-Content $_.fullname)
        $newItemtoAdd = $xml.CreateElement('newItemtoAdd')
        $newItemtoAdd.PsBase.InnerText = '1900-01-01'
        $null     = $xml.Entity.App.AppendChild($newItemtoAdd)

    $xml.SelectNodes("//Entity/App/person") | ? {
    $_.name -eq "itemToRemove"   } | % {$_.ParentNode.RemoveChildNode($_) }
       $xml.Save($_.FullName)
    }

推荐答案

Get-ChildItem D:\Projects\*.xml | % {
    [Xml]$xml = Get-Content $_.FullName

    $newItemtoAdd = $xml.CreateElement('newItemtoAdd')
    $newItemtoAdd.PsBase.InnerText = '1900-01-01'
    $xml.Entity.App.AppendChild($newItemtoAdd) | Out-Null

    $parent_xpath = '/Entity/App/person'
    $nodes = $xml.SelectNodes($parent_xpath)
    $nodes | % {
        $child_node = $_.SelectSingleNode('itemToRemove')
        $_.RemoveChild($child_node) | Out-Null
    }

    $xml.OuterXml | Out-File $_.FullName
}

这篇关于使用 Powershell 添加和删除 Xmlnode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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