How to override xml element name for collection elements using XmlAttributeOverrides?
I've got a very basic object object model that is being serialized by the System.Xml.XmlSerialization stuff. I need to use the XmlAttributeOverrides functionality to set the xml element names for a collection of child elements.
public class Foo{
public List Bars {get; set; }
}
public class Bar {
public string Widget {get; set; }
}
using the standard xml serializer, this would come out as
<Foo>
<Bars>
<Bar>...</Bar>
</Bars>
</Foo>
I need to use the XmlOverrideAttributes to make this say
<Foo>
<Bars>
<SomethingElse>...</SomethingElse>
</Bars>
</Foo>
but I can't seem to get it to rename the child elements in the collection... i can rename the collection itself... i can rename the root... not sure what i'm doing wrong.
here's the code I have right now:
XmlAttributeOverrides xOver = new XmlAttributeOverrides(开发者_JAVA技巧);
var bars = new XmlElementAttribute("SomethingElse", typeof(Bar));
var elementNames = new XmlAttributes();
elementNames.XmlElements.Add(bars);
xOver.Add(typeof(List), "Bars", elementNames);
StringBuilder stringBuilder = new StringBuilder();
StringWriter writer = new StringWriter(stringBuilder);
XmlSerializer serializer = new XmlSerializer(typeof(Foo), xOver);
serializer.Serialize(writer, someFooInstance);
string xml = stringBuilder.ToString();
but this doesn't change the name of the element at all... what am I doing wrong?
thanks
To do that you want [XmlArray]
and [XmlArrayItem]
(ideally both of to make it explicit):
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
public class Foo {
public List<Bar> Bars { get; set; }
}
public class Bar {
public string Widget { get; set; }
}
static class Program {
static void Main() {
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
xOver.Add(typeof(Foo), "Bars", new XmlAttributes {
XmlArray = new XmlArrayAttribute("Bars"),
XmlArrayItems = {
new XmlArrayItemAttribute("SomethingElse", typeof(Bar))
}
});
XmlSerializer serializer = new XmlSerializer(typeof(Foo), xOver);
using (var writer = new StringWriter()) {
Foo foo = new Foo { Bars = new List<Bar> {
new Bar { Widget = "widget"}
}};
serializer.Serialize(writer, foo);
string xml = writer.ToString();
}
}
}
Derick,
This worked for me - not sure if it's a suitable answer for you or not:
public class Foo
{
[XmlArrayItem(ElementName = "SomethingElse")]
public List<Bar> Bars { get; set; }
}
精彩评论