【问题标题】:How to detect and remove empty XML tags?如何检测和删除空 XML 标签?
【发布时间】:2015-05-27 06:16:42
【问题描述】:

我有一堆 XML 文件,我希望检测并删除其中的空标签。喜欢:

<My></My>
<Your/>

<sometags>
    <his>
    </his>
    <hasContent>sdfaf</hasContent>
</sometags>

它们是各种空标签(MyYourhis)我想删除。 PowerShell 是否支持这种空标签检测,无论它们嵌入到其他标签中有多深?

【问题讨论】:

    标签: xml powershell tags


    【解决方案1】:
    function Format-XML
    { 
        param (
            [parameter(Mandatory = $true)][xml] $xml, 
            [parameter(Mandatory = $false)][int] $indent = 4
        ) 
    
        try
        {
            $Error.Clear()
    
            $StringWriter = New-Object System.IO.StringWriter 
            $XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter 
            $xmlWriter.Formatting = "indented" 
            $xmlWriter.Indentation = $indent 
            $xml.WriteContentTo($XmlWriter) 
            $XmlWriter.Flush() 
            $StringWriter.Flush() 
    
            return $StringWriter.ToString() 
        }
    
        catch
        {
            Write-Host "$($MyInvocation.InvocationName): $_"; return $null
        }
    }
    
    
    $xml = [xml] @"
    <document>
        <My></My>
        <Your/>
        <sometags>
            <his>
            </his>
            <hasContent>sdfaf</hasContent>
        </sometags>
    </document>
    "@
    
    # The "magic" part is in this XPath expression
    
    $nodes = $xml.SelectNodes("//*[count(@*) = 0 and count(child::*) = 0 and not(string-length(text())) > 0]")
    
    $nodes | %{
        $_.ParentNode.RemoveChild($_)
    }
    
    Format-Xml $xml
    

    【讨论】:

    • 谢谢,但您能帮忙解释一下神奇的 XPath 字符串的 3 个子部分吗?
    • 作为旁注,Jeffrey Snover 更新了 article,他在其中发布了格式化功能,并提出了来自 Lee Holmes 的更巧妙的建议:$xml.Save([Console]::Out)
    • 看到 [xml] 的 $xml.Save 不存在,我刚试过:$xml = @" sdfaf "@ $x=[xml]$xml $x.Save([Console]::Out) documentMyMyYour /sometagshishishasContentsdfafhasContentsometagsdocument
    【解决方案2】:

    我不熟悉powershell,所以对@DavidBrabant 的好答案只有一点补充,特别是在xpath 部分。用于检测空元素的 xpath 可以更简单一些:

    //*[not(@*) and not(*) and normalize-space()]
    

    谓词([] 中的所有内容)依次检查当前元素是否没有属性、没有子元素以及没有空文本节点。

    【讨论】:

      【解决方案3】:

      您应该寻找使用 System.Xml.XmlDocument 的解决方案。但也可以使用正则表达式:

      $xml = @"
      <document>
          <My></My>
          <Your/>
          <sometags>
              <his>
              </his>
              <hasContent>sdfaf</hasContent>
          </sometags>
      </document>
      "@
      
      $xml -replace '(?:<(\w*)>\s*<\/\1>)|<(\w*)\/>', ''
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-16
        • 2012-01-26
        • 2012-02-22
        相关资源
        最近更新 更多