Jeff Mercado
Jeff Mercado

Reputation: 134841

Use the type's root name when serializing collection items

Just a contrived example but I have some classes that I want to control the names of when serialized.

[XmlRoot("item")]
public class ItemWrapper
{
    [XmlArray("parts")]
    public List<PartWrapper> Parts { get; set; }
}

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

Now when I serialize an ItemWrapper that has some Parts, I was expecting each of the PartWrapper items to be serialized using the root name ("part") but it instead uses the type's name (what it would use by default if the XmlRootAttribute wasn't specified).

<item>
  <parts>
    <PartWrapper name="foo" />
    <PartWrapper name="bar" />
  </parts>
</item>

Now I know to fix this to get what I want is to add the XmlArrayItemAttribute to the Parts property to specify the name of each of the items but I feel it's redundant. I just wanted to use the name of the type's root as I specified.

[XmlRoot("item")]
public class Item
{
    [XmlArray("parts")]
    [XmlArrayItem("part", Type=typeof(PartWrapper))]
    public List<PartWrapper> Parts { get; set; }
}

Is there a way that I can tell the serializer that I want to use the root name for the collection items? If so, how?

Why wouldn't it just use the root name? Any good reason why it shouldn't?

It was my understanding that the XmlRootAttribute allowed you to name the element exactly like an XmlElementAttribute does, only it had to be applied to the class. I guess I'm mistaken.

Upvotes: 0

Views: 203

Answers (1)

Milimetric
Milimetric

Reputation: 13549

From the documentation, it seems that XmlRootAttribute is used only when that element is the root (which is why it works for "item" in your case):

Controls XML serialization of the attribute target as an XML root element

- MSDN

It seems to me like perhaps you want XmlTypeAttribute for things that are not root.

Upvotes: 2

Related Questions