Thursday, July 9, 2009

How to read xml file in asp.net using c#...?

Hello,





There are many ways to read a XML file in C#. If the XML file isn't large, you can serialize that XML file into an Object. And access the nodes from that object. (good for small files)





Or you could use the XMLReader class that will allow you to parse the file (good for big files) You can do a search yourself for that since there are many tutorials out there.





Concerning serialize your xml file. You can use the "XmlSerializer" class which is included in .NET 2.0+ framework, and you can cast it to an object which represents your XML file...


==========================





XmlSerializer serializer = new XmlSerializer(typeof(MyXMLObject));


// A FileStream to read the XML Document.


FileStream fs = new FileStream(path, FileMode.Open);


// Declare the object variable of the type to be deserialized


MyXMLObject xmlObject = (MyXMLObject)serializer.Deserialize(fs);


// Close the File Stream


fs.Close();


==========================


Your MyXMLObject has the object structure which resembles the object that will be serialized. We cast the serialized object to the Stream and we get an XML object that we can use. Basically each node is a class. You have to take look at: http://msdn2.microsoft.com/en-us/library... since it is too much to explain here.





This is how we use the object..





Console.WriteLine("{0}",xmlObject.Firs...





Notice how it is like? It is very easy to traverse the nodes if they are serialized.





Good Luck


No comments:

Post a Comment