all groups > dotnet xml > december 2003 >
You're in the

dotnet xml

group:

XmlRootAttribute ignored when serializing class from array



XmlRootAttribute ignored when serializing class from array Dave
12/26/2003 7:41:04 AM
dotnet xml: Hello,

I'm trying to solve an XML serialization problem that
appears to me to be be a bug with the XmlSerializer.
Let's say I have a class that looks like this:

[XmlRootAttibute(ElementName="x"]
public class y
{
[XmlAttribute("a")] public string a;
[XmlAttribute("b")] public string b;
}

And I create an array of y using standard syntax:

y [] yArray = new y[2];

If I pass yArray directly to an XmlSerializer object for
serialization, the serializer ignores the
XmlRootAttribute setting on the class and serializes it
as "y" instead of x. Somehting like this:

<yArray>
<y a="1" b="2"/>
<y a="3" b="4"/>
<yArray>

However, if I encapsulate that array into another class,
and then serialize the containing class, it works
properly.

[XmlRootAttribute(ElementName="x_list")]
public class z
{
z()
{
y = new y[2];
}
[XmlElement("x")] public y[] yArray;
}

This serializes y to x the way I want it to:

<x_list>
<x a="1" b="2"/>
<x a="3" b="4"/>
<x_list>

I've tried overriding the XmlSerializer to no avail. Why
doesn't it pick up the XmlRootAttribute from the
declaration of the class y when it is placed into an
array and serialized directly? I'd like to not have to
encapsulate the array into another class.
XmlRootAttribute ignored when serializing class from array Dave
12/26/2003 8:03:28 AM
A slight fix:

[XmlRootAttribute(ElementName="x_list")]
public class z
{
z()
{
yArray = new y[2]; //<<<fixed to yArray.
}
[XmlElement("x")] public y[] yArray;
}

[quoted text, click to view]
AddThis Social Bookmark Button