1

I have an XML of the format like here: http://pastie.org/1311506 (not inserting it here because comment parser deletes tags).

This XML is serealized/deserialized using the following code:

[XmlRoot("products")]
public class Products
{
    [XmlElement("label")]
    public string Label { get; set; }

    [XmlArray("cars")]
    [XmlArrayItem("car")]
    public Car[] Cars { get; set; }
}

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

...

var products = new Products
                   {
                       Label = "1",
                       Cars = new[]
                                  {
                                      new Car {Name = "BMW"},
                                      new Car {Name = "Volvo"}
                                  }
                   };
var serializer = new XmlSerializer(typeof(Products));
var writer = new StringWriter();
serializer.Serialize(writer, products);
Console.WriteLine(writer);

I need an additional attribute to <cars> node called type (like here: http://pastie.org/1311514). How can I do it?

In other words, how to define data classes (Products and Car and maybe others if necessary) in order to parse XML of the format shown in the second pastie link?

DNNX
  • 6,215
  • 2
  • 27
  • 33

1 Answers1

4

There's no easy way to do that, because for collections the XmlSerializer ignores all members, it only serializes the items of the collection. However, if you only want to deserialize it and ignore the type attribute, it's not an issue : unknown attributes will just be ignored.

If you need to get the value of type, you can declare a class that is not a collection, but contains the collection. Something like that:

public class Cars
{
    [XmlElement("car")]
    public Car[] Items { get; set; }

    [XmlAttribute("type")]
    public string Type { get; set; }
}

In your Products class, just declare the Cars property of type Cars with just a XmlElement attribute:

[XmlRoot("products")]
public class Products
{
    [XmlElement("label")]
    public string Label { get; set; }

    [XmlElement("cars")]
    public Cars Cars { get; set; }
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758