gpt4 book ai didi

c# - 如何删除所有空的 XElements

转载 作者:数据小太阳 更新时间:2023-10-29 01:47:33 24 4
gpt4 key购买 nike

这个有点棘手。假设我有这个 XmlDocument

<Object>
<Property1>1</Property1>
<Property2>2</Property2>
<SubObject>
<DeeplyNestedObject />
</SubObject>
</Object>

我想找回这个

<Object>
<Property1>1</Property1>
<Property2>2</Property2>
</Object>

由于 <SubObject> 的每个 child 都是我想摆脱的空元素。具有挑战性的是您无法在遍历节点时删除节点。任何帮助将不胜感激。

更新这是我最后的结果。

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我放在一起的项目。

最佳答案

它会很慢,但你可以这样做:

XElement xml;
while (true) {
var empties = xml.Descendants().Where(x => x.IsEmpty && !x.HasAttributes).ToList();
if (empties.Count == 0)
break;

empties.ForEach(e => e.Remove());
}

为了加快速度,您可以在第一次迭代后向上遍历父节点,看看它们是否为空。

XElement xml;
var empties = xml.Descendants().Where(x => x.IsEmpty && !x.HasAttributes).ToList();
while (empties.Count > 0) {
var parents = empties.Select(e => e.Parent)
.Where(e => e != null)
.Distinct() //In case we have two empty siblings, don't try to remove the parent twice
.ToList();

empties.ForEach(e => e.Remove());

//Filter the parent nodes to the ones that just became empty.
parents.RemoveAll(e => e.IsEmpty && !e.HasAttributes);
empties = parents;
}

关于c# - 如何删除所有空的 XElements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11052420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com