views:

20

answers:

1

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"&gt;foo&lt;/FooElement&gt;

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>"?

A: 

I guess, XmlRootAttribute should play well with IXmlSerializable.

Dmitry Ornatsky
@Dmitry: Thanks, the XmlRootAttribute worked as expected.
Pag Sun