简体   繁体   English

从大型XML文件中删除节点

[英]Deleting nodes from large XML files

i have a large XML document that is to large to be loaded using XmlDocument. 我有一个很大的XML文档,可以使用XmlDocument加载。 i need to go through each child of a node and check it agaisnt a condition, then delete accordingly , then finally save the document. 我需要遍历节点的每个子节点并再次检查条件,然后相应删除,然后最后保存文档。

<root>
<node id="1">
<child delete="false"/>
</node>
<node id="2">
<child delete="true"/>
</node>
</root>

for example i would want to delete node 2, and this process must be repeated hundreds of times. 例如,我想删除节点2,并且此过程必须重复数百次。

any help would be appreciated. 任何帮助,将不胜感激。 thanks. 谢谢。

Edit could someone explain how i might go about doing this. 编辑可以有人解释我如何去做。

You can use an XmlReader to sequentially read your xml ( ReadOuterXml might be useful in your case to read a whole node at a time). 您可以使用XmlReader顺序读取xml( ReadOuterXml在您的情况下一次读取整个节点可能很有用)。 Then use an XmlWriter to write out all the nodes you want to keep. 然后使用XmlWriter写出您要保留的所有节点。

See this article which compares the performances of xml parsing approaches- http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html 请参阅比较XML解析方法性能的本文-http ://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html

XmlReader turns out to be winner here.. XmlReader证明是这里的赢家。

Note, untested and I haven't used XDocument/XElements for awhile, so there may be a typo in here 请注意,未经测试,而且我已经有一段时间没有使用XDocument/XElements了,所以这里可能有错字

XDocument xdoc = XDocument.Load("path\\to\\file.xml");
IEnumerable<XElement> elementsToDelete = xdoc.Descendants("node")
   .Where(node => node.Descendants("child")
       .Where(child => child.Attribute("delete") != null && 
       child.Attribute("delete").Value.ToLower() == "true"));
foreach(XElement element in elementsToDelete)
    element.Remove();

xdoc.Save("path\\to\\new\\file.xml");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM