WPalombini
WPalombini

Reputation: 981

How to Serialize to a "Collection with an Attribute" Using the XML Serializer

I have this model:

[XmlArray(ElementName = "Listing")]
[XmlArrayItem(ElementName = "Classification")]
public List<Classification> classifications { get; set; }

[XmlRoot("Listing")]
public class Classification
{
     [XmlAttribute("Name")]
     public string name { get; set; }

     [XmlText]
     public string Value { get; set; }
}

That gives me this:

<Listing>
<Classification Name="Location">AsiaPacific</Classification>
</Listing>

How should I modify my class to get this:

<Listing reference = "MyReference">
<Classification Name="Location">AsiaPacific</Classification>
</Listing>

Upvotes: 0

Views: 51

Answers (1)

WPalombini
WPalombini

Reputation: 981

After a few (hundreds) trial and error, I got the result that I need by modifying the model to:

[XmlElement(ElementName = "Listing")]
public ClassificationWrapper classificationWrapper { get; set; }

public class ClassificationWrapper
{
    [XmlAttribute("reference")]
        public string ref= "MyReference";

        [XmlElement("Classification", typeof(Classification))]
        public List<Classification> classifications { get; set; }

public ClassificationWrapper() { this.classifications = new List<Classification>(); }
}
public class Classification
{
       [XmlAttribute("Name")]
       public string name { get; set; }

       [XmlText]
       public string Value { get; set; }
}

Upvotes: 1

Related Questions