这个有点棘手。假设我有这个 XmlDocument
<Object>
<Property1>1</Property1>
<Property2>2</Property2>
<SubObject>
<DeeplyNestedObject />
</SubObject>
</Object>
我想找回这个
<Object>
<Property1>1</Property1>
<Property2>2</Property2>
</Object>
由于每个孩子<SubObject>
都是空元素,我想摆脱它。使其具有挑战性的是,您无法在迭代节点时删除它们。任何帮助将非常感激。
更新这就是我的结论。
public XDocument Process()
{
//Load my XDocument
var xmlDoc = GetObjectXml(_source);
//Keep track of empty elements
var childrenToDelete = new List<XElement>();
//Recursively iterate through each child node
foreach (var node in xmlDoc.Root.Elements())
Process(node, childrenToDelete);
//An items marked for deletion can safely be removed here
//Since we're not iterating over the source elements collection
foreach (var deletion in childrenToDelete)
deletion.Remove();
return xmlDoc;
}
private void Process(XElement node, List<XElement> elementsToDelete)
{
//Walk the child elements
if (node.HasElements)
{
//This is the collection of child elements to be deleted
//for this particular node
var childrenToDelete = new List<XElement>();
//Recursively iterate each child
foreach (var child in node.Elements())
Process(child, childrenToDelete);
//Delete all children that were marked as empty
foreach (var deletion in childrenToDelete)
deletion.Remove();
//Since we just removed all this nodes empty children
//delete it if there's nothing left
if (node.IsEmpty)
elementsToDelete.Add(node);
}
//The current leaf node is empty so mark it for deletion
else if (node.IsEmpty)
elementsToDelete.Add(node);
}
如果有人对此用例感兴趣,那就是我放在一起的ObjectFilter项目。