Etienne Noël
Etienne Noël

Reputation: 6166

Serialize c# object in XML using variable content as attribute name

I have the following c# object:

class Modification {
    public string Name;
    public string Value;
}

I want to use the serializer to serialize my object the following way:

<name>value</name>

Example: Let's say we set those variables to

Name = "Autoroute"
Value = 53

I want the xml to look like:

<test>
    <Autoroute>53</Autoroute>
</test>

I saw somewhere that this feature is not supported by the serializer, but is there a way to overload the serializer to allow this kind of behavior ?

Changing the XML structure is not an option since it is already a convention.

Upvotes: 0

Views: 1190

Answers (1)

steve16351
steve16351

Reputation: 5812

You can use IXmlSerializable to do this, though this doesn't give you control over the root element name - you have to set this in the serializer (which may present other challenges when you come to read it as part of a larger xml structure...).

public class Modification : IXmlSerializable
{
    public string Name;
    public string Value;

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

    public void ReadXml(System.Xml.XmlReader reader)
    {
        reader.ReadStartElement();
        Name = reader.Name;
        Value = reader.ReadElementContentAsString();
        reader.ReadEndElement();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteElementString(Name, Value);
    }
}

Usage,

Modification modification = new Modification()
{
    Name = "Autoroute",
    Value = "53"
};

Modification andBack = null;

string rootElement = "test";    
XmlSerializer s = new XmlSerializer(typeof(Modification), new XmlRootAttribute(rootElement));
using (StreamWriter writer = new StreamWriter(@"c:\temp\output.xml"))
    s.Serialize(writer, modification);

using (StreamReader reader = new StreamReader(@"c:\temp\output.xml"))
    andBack = s.Deserialize(reader) as Modification;

Console.WriteLine("{0}={1}", andBack.Name, andBack.Value);

The XML produced by this looks like this,

<?xml version="1.0" encoding="utf-8"?>
<test>
   <Autoroute>53</Autoroute>
</test>

Upvotes: 1

Related Questions