Удалите теги XML с пустым атрибутом в C# - PullRequest
0 голосов
/ 13 марта 2020

Я ищу хороший подход, который может эффективно удалять пустые теги, а также все теги без каких-либо атрибутов из XML.

Например, рассмотрим следующий пример xml file

  <?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>

Любая помощь очень ценится.

1 Ответ

0 голосов
/ 13 марта 2020

Вы можете сделать следующее (комментарии в коде).

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();

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...