[英]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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.