XPath in .Net


Hi,

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
<DEALS>
<DEAL>
<Products>
<product>Product info</product>
</Products>
</DEAL>
<DEAL>
<Products>
<product>Product info2</product>
<product>Product info3</product>
<product>Product info4</product>
</Products>
</DEAL>
</DEALS>

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


Dim file As String
file = “C:\mydata.xml”
Dim xmldoc As New XmlDocument
xmldoc.Load(file)
Dim node As XmlNode

node = xmldoc.SelectSingleNode(“//DEALS/DEAL[2]/Products/Product[2]”)
node.ParentNode.RemoveChild(node)
xmldoc.Save(file)

See the line node = xmldoc.SelectSingleNode(“//DEALS/DEAL[2]/Products/Product[2]”)

It tells the Xml document object to naviagte to Second Deal in the Deals node and than goes to its product and Pick Second Product and than using
node.ParentNode.RemoveChild(node)
I go to node parent and remove “node” child from its list and save the Document again. Now I have deleted the XML node I want with just two line of code.

Happy XMLing
Sumit Gupta