Updated on Kisan Patel
This tutorial will show you how to read all the element data and attribute values from an XML file in C#?
You need to follow below students.xml file to understand this tutorial.
<?xml version="1.0" encoding="utf-8" ?> <students> <student id="1"> <name>Kisan</name> <city country="India">Ladol</city> </student> <student id="2"> <name>Ravi</name> <city country="US">Vijapur</city> </student> <student id="3"> <name>Ujas</name> <city country="India">Ladol</city> </student> <student id="4"> <name>Ketul</name> <city country="England">Ladol</city> </student> </students>
By using below line of C# code to read data for a single element by specifying the name of the element.
XmlReader xr = XmlReader.Create("D:\\students.xml"); while (xr.Read()) { if (xr.NodeType == XmlNodeType.Text) { Console.WriteLine(xr.Value); } }
..output of the above program…
In the above example, we have create object of the XmlReader
class by calling its Create()
method and passing the path of the XML file (students.xml) as parameter to it. We have then traversed the nodes of the XML document by using the Read()
method of the XmlReader
object in a while loop. Inside the loop, we have compared its NodeType
with the values from the XmlNodeType
enumeration for each node. If it is a text node, we are write the text value to the console.
Now, by using below line of code you can get value of specific element of xml.
XmlReader xr = XmlReader.Create("D:\\students.xml"); while (xr.Read()) { if (xr.NodeType == XmlNodeType.Element && xr.Name == "city") { Console.WriteLine(xr.ReadElementContentAsString()); } else { xr.Read(); } }
..output of the above program…
In above code, we have checked if the current node is of type XmlNodeType.Element
, and its name is city. If it is, we write the text value of the element to the console using the ReadElementContentAsString()
method of the XmlReader
object. If not, we move to the next node by using the Read()
method of the XmlReader object.
Now, by using below line of code you can get value of attribute of the specific element of xml.
XmlReader xr = XmlReader.Create("D:\\students.xml"); while (xr.Read()) { if (xr.NodeType == XmlNodeType.Element && xr.Name == "city") { for (int i = 0; i < xr.AttributeCount; i++) { Console.WriteLine(xr.GetAttribute(i)); } } }
..output of the above program…
In above code, we have checked if the current node is of type XmlNodeType.Element
. If it is, then we will write all its attributes to the console.