简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM