Deleting nodes from large XML files

i have a large XML document that is to large to be loaded using 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.

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). Then use an XmlWriter to write out all the nodes you want to keep.


See this article which compares the performances of xml parsing approaches- http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html

XmlReader turns out to be winner here..


请注意,未经测试,我还没有使用XDocument/XElements一段时间,所以在这里可能会出现拼写错误

XDocument xdoc = XDocument.Load("pathtofile.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("pathtonewfile.xml");
链接地址: http://www.djcxy.com/p/64742.html

上一篇: XMLReader是SAX解析器,DOM解析器还是两者都不是?

下一篇: 从大型XML文件中删除节点