views:

43

answers:

2

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:

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

A: 

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);
    }
itsho
That code produces: `<ClassB><ClassB>Test</ClassB></ClassB>`when I'd really like:`<ClassB>Test<ClassB>`
Pakman
so, you can use WriteString instead of WriteElementString :-). *edit* - just saw someone else said the same :-(
itsho
+1  A: 

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.

Peter
Ahh, you've shown me the problem! I was using `WriteElementString("Value", _value)` instead of `WriteString(_value)`. Now my XML looks the way I want it: `<ClassB>Test</ClassB>`
Pakman