简体   繁体   English

Powershell 从 xml 文件中删除空节点

[英]Powershell Delete empty nodes from xml file

I need to delete empty nodes from xml file.我需要从 xml 文件中删除空节点。

ex:前任:

     <Keys>
      <Key Name="Topic" />
      <Key Name="Topic" />
      <Key Name="Topic" />
      <Key Name="Keyword" />
      <Key Name="Keyword" />
      <Key Name="Keyword" />
      <Key Name="Keyword">Musk deer</Key>
      <Key Name="Keyword">Hunting</Key>
      <Key Name="Keyword">Trapping</Key>
      <Key Name="Keyword">Mythology</Key>
      <Key Name="Topic">Traditional narrative</Key>
    </Keys>

The idea is remove this nodes:这个想法是删除这个节点:

      <Key Name="Topic" />
      <Key Name="Topic" />
      <Key Name="Topic" />
      <Key Name="Keyword" />
      <Key Name="Keyword" />
      <Key Name="Keyword" />

Any suggestion, to help me on this?有什么建议可以帮助我吗?

Best最好的

You can use XML Object in PowerShell like this:您可以像这样在 PowerShell 中使用 XML Object :

$FileContent = New-Object -Typename XML
# Load file
$FileContent.Load("C:\Temp\in.xml")
$Nodes = $FileContent.SelectNodes("//Key")
# For each node
foreach ($Node in $Nodes) {
    if ($Node.InnerXml -ne "") {
        $Node.ParentNode.RemoveChild($Node)
    }
}
# Save file in UTF-8
$ConfigFileEncoding = New-Object System.Text.UTF8Encoding($false)
$ConfigFileWriter = New-Object System.XML.XMLTextWriter("C:\Temp\out.xml", $ConfigFileEncoding)
$ConfigFileWriter.Formatting = 'Indented'
$FileContent.Save($ConfigFileWriter)
$ConfigFileWriter.Close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM