Ivan Prodanov
Ivan Prodanov

Reputation: 35532

How to avoid creating a new class for each xml attribute while deserializing?

I've taken the approach to deserialize xml as objects, but some of the nodes are relatively small and I find it weird to create a class for such. Let me give an example:

public class Plugin
{
    ...
    List<Foo> Foos{ get; set; }
    List<Bar> Bars{ get; set; }
    ...
}

[Serializable]
public class Foo
{
    [XmlText()]
    public string PluginId { get; set; }
}

[Serializable]
public class Bar
{
    [XmlAttribute("Name")]
    public string Name { get; set; }
}

It's just how it is defined in the XML schema

<Plugin>
  <Foos>
    <Foo>Some Text</Foo>
    <Foo>Some More Text</Foo>
  </Foos>
  <Bars>
    <Bar Name="Some Name"/>
    <Bar Name="Some Other Name"/>
  </Bars>

Isn't there an attribute that I could set in the Plugin class on those 2 fields that would let me do the magic without creating 2 classes containing 1 field each?

Upvotes: 0

Views: 40

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063499

The Foos could could

[XmlArray("Foos"), XmlArrayItem("Foo")]
public List<string> Foos {get; set;}

The Bar, however, must remain - you can't configure the attribute otherwise.

Upvotes: 1

Related Questions