0

I need to set an attribute in my XML. I require the following:

<finAccount version="1.00">

Here is my model so far

[XmlAttribute("version")]
[XmlType("finPOWERConnect")]
public class ApplicationData
{
    public List<Account> Accounts;
}

[XmlType("finAccount")]
public class Account
{
   //Account stuff
}

The following function serialises my object to xml using the above model.

 public Boolean SerialiseObjectToXmlString(Object obj, ref string xml)
    {
        System.IO.MemoryStream ms = null;
        bool Ok = true;
        XmlSerializer xmlSerializer = null;

        xml = "";

        //Serialise
        try
        {
            xmlSerializer = new XmlSerializer(obj.GetType());
            ms = new MemoryStream();
            xmlSerializer.Serialize(ms, obj);
            xml = System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
            ms.Close();
        }

        catch(Exception ex)
        {
            Ok = false;
            xml = ex.Message;
        }

        finally
        {
            if (ms != null) ms.Dispose();
        }

        return Ok;
    }

I have looked at several examples that set the attribute in the above method however I use this method all throughout the application. Is there a way to set the xml attribute (version="1.00) in the model?

CodeMonkey
  • 119
  • 4
  • 12
  • Can you clarify your model? 1) Your `ApplicationData` class does not compile, since [`XmlAttributeAttribute`](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributeattribute%28v=vs.110%29.aspx) can only be applied to a property, indexer, field, parameter or return. 2) What is `finAccount`, and what is its relationship to `ApplicationData`? – dbc May 20 '15 at 04:39
  • @dbc I came accross the XmlAttribute in an example and added it in an attempt to get it to work. I also fixex up the model above. Does this help? Thx. – CodeMonkey May 20 '15 at 05:08
  • So you have a list of `Account` classes, all of which need to have an attribute `"version"`, which is always "1.00" (and thus is repeated many times in the XML)? – dbc May 20 '15 at 05:21

1 Answers1

0

Try this. Class should be XmlRoot and arrays should be XmlElement. The XmlElement avoids adding two layer of the same tag to code. Try without XmlElement and you will see the difference.

[XmlRoot("finPOWERConnect")]
public class ApplicationData
{
    [XmlElement("finAccount")]
    public List<Account> Accounts {get; set; }
}

[XmlRoot("finAccount")]
public class Account
{
    [XmlAttribute("version")]
    public string Version { get; set; } 
    //Account stuff
}
​
jdweng
  • 33,250
  • 2
  • 15
  • 20