Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML serialization in .net

I'm trying to serialize an object to meet another systems requirements.

It need to look like this:

<custom-attribute name="Colour" dt:dt="string">blue</custom-attribute>

but instead is looking like this:

<custom-attribute>blue</custom-attribute> 

So far I have this:

[XmlElement("custom-attribute")]
public String Colour{ get; set; }

I'm not really sure what metadata I need to achieve this.

like image 647
g.foley Avatar asked May 19 '26 02:05

g.foley


1 Answers

You could implement IXmlSerializable:

public class Root
{
    [XmlElement("custom-attribute")]
    public Colour Colour { get; set; }
}

public class Colour : IXmlSerializable
{
    [XmlText]
    public string Value { get; set; }

    public XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("dt:dt", "", "string");
        writer.WriteAttributeString("name", "Colour");
        writer.WriteString(Value);
    }
}

class Program
{
    static void Main()
    {
        var serializer = new XmlSerializer(typeof(Root));
        var root = new Root
        {
            Colour = new Colour
            {
                Value = "blue"
            }
        };
        serializer.Serialize(Console.Out, root);
    }
}
like image 190
Darin Dimitrov Avatar answered May 21 '26 16:05

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!