Jus*_*mes 14 xml powershell powershell-2.0 xml-parsing
我试图添加和删除多个xml文件中的元素.我遇到了两个问题.它自动删除空元素,然后它没有删除我想要的东西
我有这样的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>
Run Code Online (Sandbox Code Playgroud)
我想要的是什么
<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>
Run Code Online (Sandbox Code Playgroud)
我在上面的输出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>
Run Code Online (Sandbox Code Playgroud)
删除了我不希望发生的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)
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*sht 19
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
}
Run Code Online (Sandbox Code Playgroud)
要从目录中的所有 xml 文件中删除节点,并将结果另存为新的 xml 文件,我使用以下 powershell 脚本:
Get-ChildItem .\*.xml | % {
[Xml]$xml = Get-Content $_.FullName
$xml | Select-Xml -XPath '//*[local-name() = ''itemToRemove'']' | ForEach-Object{$_.Node.ParentNode.RemoveChild($_.Node)}
$xml.OuterXml | Out-File .\result.xml -encoding "UTF8"
}
Run Code Online (Sandbox Code Playgroud)
注意:“local-name”-语法用于忽略命名空间。
| 归档时间: |
|
| 查看次数: |
24704 次 |
| 最近记录: |