c# - Removing XML node -
i have got yet task not able accomplish: supposed parse xml this site, remove nodes don't have "video" in name , save xml file. have no problems reading , writing, removing makes me difficulties. have tried node -> parent node -> child node work-aroud, did not seem useful:
static void main(string[] args) { using (webclient wc = new webclient()) { string s = wc.downloadstring("http://feeds.bbci.co.uk/news/health/rss.xml"); xmlelement tbr = null; xmldocument xml = new xmldocument(); xml.loadxml(s); foreach (xmlnode node in xml["rss"]["channel"].childnodes) { if (node.name.equals("item") && node["title"].innertext.startswith("video")) { console.writeline(node["title"].innertext); } else { node.parentnode.removechild(node); } } xml.save("newxmldoc.xml"); console.writeline("\ndone..."); console.read(); } }
i have tried removeall method, not work well, because removes nodes not satisfying "video" condition.
//same code above, else statement changed else { node.removeall(); }
could me, please?
i find linq xml easier use
var xdoc = xdocument.load("http://feeds.bbci.co.uk/news/health/rss.xml"); xdoc.descendants("item") .where(item => !item.element("title").value.startswith("video")) .tolist() .foreach(item=>item.remove()); xdoc.save("newxmldoc.xml");
you can use xpath
foreach (var item in xdoc.xpathselectelements("//item[not(starts-with(title,'video:'))]") .tolist()) { item.remove(); }
Comments
Post a Comment