How to change the tag name of the serialized XML element via IXmlSerializable
Some background:
We have some entity开发者_开发知识库 classes need to be serialized, so we implement the entity class as following in the first edition:
[XmlType("FooElement")]
public class Foo
{
[XmlText]
public string Text { get; set; }
}
The serialized XML string should be:
<?xml version="1.0" encoding="gb2312"?>
<FooElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" mlns:xsd="http://www.w3.org/2001/XMLSchema">foo</FooElement>
But we need to make the Text property as read only, so we change the Foo class to implement the IXmlSerializable interface as following:
[Serializable]
public class Foo : IXmlSerializable
{
public Foo()
{ }
public Foo(string text)
{
Text = text;
}
public string Text { get; private set; }
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
Text = reader.Value;
}
public void WriteXml(XmlWriter writer)
{
writer.WriteValue(Text);
}
}
Then the serialized XML string was also changed as following:
<?xml version="1.0" encoding="gb2312"?><Foo>foo</Foo>
Is there any way to change the tag name from "<Foo>foo</Foo>
" to "<FooElement>foo</FooElement>
"?
I guess, XmlRootAttribute should play well with IXmlSerializable.
精彩评论