3

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.

1 Answer 1

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This was too hard to implement based on the amount of customised xml I needed to do. So I created a simpler hack solution. This seems like the right way. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.