sunshine



XML manipulation with XmlDocument

Let’s take a simple example.

<Students>
          <Student type='Exchange'>Mark Twain</Student> 
</Students>

Following code will read the student name and type of the student.

XmlDocument doc = new XmlDocument();
            doc.LoadXml(@"<Students><Student type='Exchange'>Mark Twain</Student></Students>");
XmlNode rootNode = doc.FirstChild;

string studentName1 = rootNode.FirstChild.InnerText;
string studentType1 = rootNode.FirstChild.Attributes["type"].Value;

As you can see after loading the XML, the FirstChild will take you to the root level ( Students) and then FirstChild of the root will take you to the student. Each node got an attribute collection property which will give you the attributes on that node. Now lets add one more student to the XML.


<Students>
   <Student type='Exchange'>Mark Twain</Student> 
   <Student type='Exchange'>Jane Austin </Student>
</Students>

We can read both students as follows.

XmlDocument doc = new XmlDocument();
            doc.LoadXml(@"<Students><Student type='Exchange'>Mark Twain</Student><Student type='Normal'>Jane Austin </Student></Students>");
XmlNode rootNode = doc.FirstChild;

string studentName1 = rootNode.FirstChild.InnerText;
string studentType1 = rootNode.FirstChild.Attributes["type"].Value;

XmlNode node = rootNode.FirstChild.NextSibling;
string studentName2 = node.InnerText;
string studentType2 = node.Attributes["type"].Value;


So we are reading the first child's sibling and accessing the data of that node. If you want to read the next student, get the NextSibling of the last node. You can iterate through all the children through ChildNodes property as follows.(First three lines of code on the above example should be added to the front of this code)


List<String> students = new List<string>();
   foreach(  XmlNode x in rootNode.ChildNodes)
   {
     students.Add(x.InnerText);
   }

We offer one on one C# training,SQL training,WCF training,WPF training,WinForms training, MVC training, ASP.NET training, Ajax & Javascript training. Please see the contacts page