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.

1

1 Answer 1

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

3 Comments

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?
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.
Thats exactly what i wanted to hear.

Your Answer

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