在 C# 中删除具有空属性的 XML 标签

Remove XML tags with empty attribute in C#

我正在寻找一种可以有效地从 XML 中删除空标签以及所有没有任何属性的标签的好方法。

例如, 考虑以下示例 xml 文件

  <?xml version="1.0"?>
<Root xmlns:xsd="" xmlns:xsi="" name="">
  <Branches>
    <Branch name="TEST">     
      <Branches>
    <parametrs/>
    <Branch name="abc"/>
        <Branch name="Subtest">
          <Branches>
            <Branch name="sample">      
            </Branch>
          </Branches>
        </Branch>
 </Branches>
  </Branch>    
</Branches>
<Branches>
    <Branch name="TEST1">
      <Branches>
        <Branch name="Subtest">
          <Branches>
            <Branch name="sample">      
            </Branch>
          </Branches>
        </Branch>
 </Branches>
  </Branch>    
</Branches> 
</Root>

可能成为:

<?xml version="1.0"?>
<Root xmlns:xsd="" xmlns:xsi="" name="">
<Branch name="TEST">     
    <Branch name="abc"/>
        <Branch name="Subtest">   
            <Branch name="sample"/>        
        </Branch>
</Branch>    
<Branch name="TEST1">  
  <Branch name="Subtest">
      <Branch name="sample"/>         
  </Branch>
</Branch>    
</Root>

非常感谢任何帮助。

您可以执行以下操作(代码中的注释)。

var xdoc = XDocument.Parse(xml);
var nodesToRemove = new List<XElement>();

// Get the List of XElements that do not have any attributes and iterate them
foreach(var node in xdoc.Descendants().Where(e => !e.HasAttributes))
{
    // If any XElement has children, move them up
    if(node.Elements().Any())
    {
        node.Parent.Add(node.Elements());

    }
    // Mark the node for removal
    nodesToRemove.Add(node);
}

// Remove the marked nodes
foreach(var item in nodesToRemove)
{   
    item.Remove();
}

var resultXml = xdoc.ToString();