4

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..

2
  • I am guessing you mean you want to serialize xml into an object not just load it into an xmlDocument object, correct? Commented Oct 8, 2009 at 13:42
  • @CSharpAtl: I misunderstood it too; Commented Oct 8, 2009 at 13:49

3 Answers 3

9

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);
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. I heard LINQ is more efficient.
5

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;
}

Comments

1
  1. Take the schema (or an xml file) and generate a class from that with xsd.exe. The generated code will be ugly, you may need to clean it up by hand.
  2. Use XmlSerializer to deserialize into an instance.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.