I would like to parse an XML file and save this information into object. What is the best way to do this? Please let me know.
Thank you..
I would like to parse an XML file and save this information into object. What is the best way to do this? Please let me know.
Thank you..
You could use XmlSerializer to deserialize it.
using System;
using System.IO;
using System.Xml.Serialization;
[XmlRoot("Root")]
public class MyType
{
[XmlElement("Id")]
public string Id { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
}
static class Program
{
static void Main()
{
string xml = @"<Root>
<Id>1</Id>
<Name>The Name</Name>
</Root>";
MyType obj = (MyType) new XmlSerializer(typeof(MyType))
.Deserialize(new StringReader(xml));
Console.WriteLine(obj.Id);
Console.WriteLine(obj.Name);
}
};
If you are using .Net 3.5, I would suggest using LINQ-To-XML.
A simple example...
XML file
<?xml version="1.0" ?>
<People>
<Person>
<Name> ABC </Name>
<SSN> 111111 </SSN>
<Address> asdfg </Address>
</Person>
</People>
LINQ query
XDocument doc = XDocument.Load(pathToFile);
var query = from d in doc.Root.Descendants("Person")
select d;
foreach (var q in query)
{
string name = q.Element("Name").Value;
string ssn = q.Element("SSN").Value;
string address = q.Element("Address").Value;
}
The advantage of this method over others is that you get a strongly typed object (and IntelliSense working on your object). Among other things it means that the "node lookup" is faster than at other solutions (which mostly use a dictionary).
Or you might give a try to dynamic keyword of C# 4.0, it may give you a choice to avoid generating the code and just deserialize at runtime. I'm not sure about that though. That way you lose strong typing, but keep the syntax.