Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing XML, how do I access attributes?

I have some XML that I am consuming and deserializing.

<Foo>
    <Bars Baz="9">
        <Bar>...</Bar>
        <Bar>...</Bar>
    </Bars>
</Foo>

Currently I deserialize it to this class:

[XmlRoot("Foo")]
public class Foo
{
    public Foo() { }

    [XmlArrayItem("Bar")]
    public Bar[] Bars { get; set; }
}

This works fine, except that I don't capture the value of @Baz. I want to add Baz as a property of Foo, but I'm not sure how. What attribute would I set on my Baz property to properly deserialize the xml?

[WhatAttributeGoesHere("?")]
public int Baz { get; set; }
like image 987
gilly3 Avatar asked May 14 '11 18:05

gilly3


1 Answers

Normally:

[XmlAttribute]

(with optional name, namespace, etc) is what you are after.

However, you can't use that directly on a collection. You would need instead to have a wrapper class for Bars, with the attribute and a:

public class Foo {
    public BarWrapper Bars {get;set;}
}
public class BarWrapper {
    private readonly List<Bar> bars = new List<Bar>();
    [XmlElement("Bar")]
    public List<Bar> Items {get{return bars;}}

    [XmlAttribute]
    public int Baz {get;set;}
}
public class Bar {...}
like image 80
Marc Gravell Avatar answered Nov 05 '22 17:11

Marc Gravell