开发者

Serialize class's ToString() value as XmlElement

In C#, I'm trying to serialize ClassA into XML:

[Serializable]
public ClassA 
{
    [XmlElement]
    public string PropertyA { get; set; } // works fine

    [XmlElement]
    public ClassB MyClassB { get; set; }
}

[Serializable]
public ClassB
{
    private string _value;

    public override string ToString()
    {
        return _value;
    }
}

Unfortunately, the serialized result is:

开发者_C百科
<PropertyA>Value</PropertyA>
<ClassB />

Instead, I want it to be:

<PropertyA>Value</PropertyA>
<ClassB>Test</ClassB>

...assuming _value == "Test". How do I do this? Do I have to provide a public property in ClassB for _value? Thanks!

UPDATE:

By implementing the IXmlSerializable interface in ClassB (shown here #12), the following XML is generated:

<PropertyA>Value</PropertyA>
<ClassB>
    <Value>Test</Value>
</ClassB>

This solution is almost acceptable, but it would be nice to get rid of the tags. Any ideas?


As you indicated, the only way to do this is to implement the IXmlSerializable interface.

public class ClassB : IXmlSerializable
{
    private string _value;

    public string Value {
        get { return _value; }
        set { _value = value; }
    }

    public override string ToString()
    {
        return _value;
    }

    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        _value = reader.ReadString();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteString(_value);
    }

    #endregion
}

Serializing the following instance...

ClassB classB = new ClassB() { Value = "this class's value" };

will return the following xml :

<?xml version="1.0" encoding="utf-16"?><ClassB>this class's value</ClassB>

You might want to do some validations so that you encode xml tags etc.


You've answered yourself. if you derive from IXmlSerializable, you can change the method to do exactly (hopefully) what you wish:

    public void WriteXml(System.Xml.XmlWriter writer)
    {
         writer.WriteElementString("ClassB",_value);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜