The XML handling in C# believe me is one of the tricky task.
Sometimes the way we read one of the XML will not work out for the other and will throw some exception and believe me that when you see that the same code works in one program and not the other then trust me you just feel like yelling at Visual Studio. Many times the code I write for one XML file do not works for the other and trust me that really frustrates… J
In this post I will brief about XML loading and how to query XML for 2 most frequently used requirements:
1. Getting a particular node.
2. Getting a particular node along with its child nodes.
So XML handling starts with loading the XML Document.
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@”C:\Documents and Settings\Administrator\Desktop\Test Sprint\URL_Config\Test.xml”);
Now the problem starts after loading the document. The problem is with the namespace. Sometimes the document gets loaded properly and sometimes does not. So we need to create a namespace in that document (xDoc here).
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
Getting a particular node:
To get a particular node we can use the “GetElementsByTagName” method. This method returns the list of nodes having the same tag name as specified.
categorynodeList = xDoc.GetElementsByTagName(“Category”);
Getting a particular node along with its child nodes:
But to get the list of nodes along with child nodes we need to use bit complex xquery.
nodeList = root.SelectNodes(“//sm:Feed/sm:Item”, nsmgr);
It requires one to think smartly of the trees present and how to query to get the node list. There are 2 ways of getting the node list.
1. Using the “GetElementsByTagName” method .
2. Using the “SelectNodes” method.