-1

I have XML like the following:

<feed>
  <products>
    <product>
    </product>
    .
    .
    .
    <product>
    </product>
  </products>
</feed>

I can deserialize the xml using:

public class feed
{
    public ProductList products { get; set; }
}

public class ProductList
{
    [XmlElement("product")]
    public List<Product> Products { get; set; }
}

var result = (feed)new XmlSerializer(typeof(feed)).Deserialize(xmlReader);

I thought I can use the XML root attribute to control deserialization, i.e,

class Products
{
   public List<Product> Products { get; set; }
}

var rootAtrr = new XmlRootAttribute("products");
var result = (Products)new XmlSerializer(typeof(Products), rootAtrr).Deserialize(xmlReader);

or better still:

var result = (List<Product>)new XmlSerializer(typeof(List<Product>), rootAtrr).Deserialize(xmlReader);

All the above changes don't work.

Does that mean the root attribute is specifically for ACTUAL root element in XML not where to start reading?

Also, does that mean the XML document enforce what model class to define? the feed class in this particular case?

Or am I missing a point or 3?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
rethabile
  • 3,029
  • 6
  • 34
  • 68

1 Answers1

1

The "root element" in XML lingo means the top level element of the XML document. The XmlRootAttribute instructs the XmlSerializer how your class maps to/from the root element of an XML document.

If, for example, the XML root element should have the tag name feed, but you would rather have your class named SerializedFeed, you could use the XmlRootAttribute, like this:

[XmlRoot("feed")]
public class SerializedFeed
{
    [XmlArray("products")]
    [XmlArrayItem("product")]
    public List<Product> products { get; set; }
}

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

And read the XML like this:

var xml = @"<feed>
  <products>
    <product name=""A"" />
    <product name=""B"" />    
  </products>
</feed>";
var serializer = new XmlSerializer(typeof(SerializedFeed)); 
var feed = (SerializedFeed)serializer.Deserialize(new StringReader(xml));

When using the XmlSerializer, your class hierarchy should match the XML document. If it does not, in my experience you'll be fighting the framework at every turn, and it would be easier to write your own serializer/deserializer using the XmlReader/XmlWriter API.

gnud
  • 77,584
  • 5
  • 64
  • 78