How To: Using XPath in .Net Application (Deleting a Node from XML)
Author : Sumit Gupta
Recently, I was working on XML Parsing using ASP.Net. In this I have to AED (Add/edit/delete) Nodes as user enter data, I am comfortable with adding nodes as I have to create Element and just do...
objXml.AppendChild(newchildnode)
it works find, but when I have to delete which is more conditional and for me is not as simple to delete as adding new node...
My XML is something like this
Now in this XML I have to delete the Product Info 3. One of my friends who has done it before suggest me to Iterate through each Deal and when my counter goes to node 2 just check and Loop (nested) for the products and if I found 2 item in the list delete that.
I have the node Serial No for deal and product with me, infact thats the only data I have to delete the node as as many deals can have as many products as user enter in them...
Secondly, I frequently getting error for the looping, error i got is Node I was delete is not a Child node of reference node.
Than I look for Xpath and after searching and looking for xPath in W3C site I got this piece of code
node = xmldoc.SelectSingleNode("//DEALS/DEAL[2]/Products/Product[2]").
Line above tells XmlDocument object to naviagte to Second Deal in the Deals node and than goes to its product. Once there, pick second Product in the list.
Now goto node's parent and remove "node" child from its list using this code
node.ParentNode.RemoveChild(node).
Save your XML document so that you won't lose your changes in XML. Now, we have delete our XML required XML node. I have been using XML for quite some time, I initial use to write foreach loops to
navigate through entire XML to find that node. Its not that we can use XPath for deletion, but for searching a node based on some criteria is also possible with it.
Only this much for now.