0

I need to serialize a class to xml. If a certain condition is met at run-time, I want to add an XML attribute to an element and assign it a value. Sometimes, the "Error" attribute will appear and sometimes it won't.

My code that serializes my objects:

public class XmlToolsRepo : IXmlTools
{
    public string SerializeToXML<T>(object obj)
    {
        string results = null;

        Encoding enc = Encoding.UTF8;
        using (MemoryStream ms = new MemoryStream())
        {
            using (XmlTextWriter xw = new XmlTextWriter(ms, enc))
            {
                xw.Formatting = Formatting.None;
                XmlSerializerNamespaces emptyNS = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
                XmlSerializer xSerializer = new XmlSerializer(typeof(T));
                xSerializer.Serialize(xw, obj, emptyNS);
            }

            results = enc.GetString(ms.ToArray());
        }

        return results;
    }
}

A class with a property that could have a new attribute at run-time:

[DataContract]
public class H204
{
    [DataMember]
    [XmlAttribute]
    public string Code { get; set; }

    [DataMember]
    public string DW { get; set; }
}

When a condition is met I need for the XML to look like this:

<?xml version="1.0" encoding="UTF-8"?>
<H204 Code="A">
    <DW Error="test" />
</H204>
WorkJ
  • 91
  • 16
  • Have you tried searching for dynamic xml attribues? https://stackoverflow.com/questions/36946189/c-sharp-dynamic-attributes – Train Aug 28 '19 at 15:31

1 Answers1

1

Try following :

    public class H204
    {
        [XmlAttribute(AttributeName = "Code")]
        public string Code { get; set; }

        [XmlElement(ElementName = "DW")]
        public  DW  dw{ get; set; }
    }
    public class DW
    {
        [XmlAttribute(AttributeName = "Error")]
        public string text { get; set; }
    }
jdweng
  • 33,250
  • 2
  • 15
  • 20