nav100
nav100

Reputation:

Parse XML and save into object

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

Upvotes: 4

Views: 3231

Answers (3)

Tamás Szelei
Tamás Szelei

Reputation: 23921

  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.

Upvotes: 1

Ryan Alford
Ryan Alford

Reputation: 7594

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

Upvotes: 5

Pawel Lesnikowski
Pawel Lesnikowski

Reputation: 6381

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

Upvotes: 9

Related Questions