0

Is there a way to fill out a class using XML data instead of JSON? Example in marc's excellent answer.

I would like everything to be as close to that code except the input is an xml file instead of json.

Community
  • 1
  • 1
  • possible duplicate of [How do I map XML to C# objects](http://stackoverflow.com/questions/87621/how-do-i-map-xml-to-c-objects) – John Saunders Sep 21 '10 at 20:42

1 Answers1

4

You could use XmlSerializer:

public class Foo
{
    public string Bar { get; set; }
}

class Program
{
    public static void Main()
    {
        var serializer = new XmlSerializer(typeof(Foo));
        var xml = "<Foo><Bar>beer</Bar></Foo>";
        using (var reader = new StringReader(xml))
        {
            var foo = (Foo)serializer.Deserialize(reader);
            Console.WriteLine(foo.Bar);
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • That looks right. Last time i looked at serialize code i had to put tons of attributes in the class. Is this not the case with XmlSerializer? –  Jul 08 '10 at 06:05
  • This will depend on what class you are trying to serialize/deserialize to what XML structure, but yes attributes might be needed. There's no magic. If the XML structure doesn't match your object structure you need to instruct the serializer how to handle it. – Darin Dimitrov Jul 08 '10 at 06:06
  • Thats exactly what i wanted to hear. –  Jul 08 '10 at 06:20