Question

I am trying to serialize an ObservableCollection of Code to an XML file. When I do this the resultant XML is like this:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfCode xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Code>
    <AccpacCode>ORWC</AccpacCode>
    <LAC>94199999999999999</LAC>
    <SCSCode>WC</SCSCode>
  </Code>
  <Code>
    <AccpacCode>AK9999</AccpacCode>
    <LAC>90299999999999999</LAC>
    <SCSCode>UI</SCSCode>
    <ParentEmployerAccpacCode>AKSUTA</ParentEmployerAccpacCode>
  </Code>
  <Code>
    <AccpacCode>AL0014</AccpacCode>
    <LAC>90107307000999999</LAC>
    <SCSCode>IT</SCSCode>
  </Code>
  <Code>
    <AccpacCode>IN0006</AccpacCode>
    <LAC>91817599999999999</LAC>
    <SCSCode>IT</SCSCode>
  </Code>

This is all good except I need the tag Codes in place of ArrayOfCode. How can I specify the tag name?

Here is the Codes model:

namespace SerializeObservableCollection.Model
{
    [Serializable()]
    public class Codes
    {
        public Codes() { }

        [XmlElement("Code")]
        public ObservableCollection<Code> CodeCollection { get; set; }

    }

    [Serializable()]
    public class Code
    {
        [XmlElement("AccpacCode")]
        public string AccpacCode { get; set; }

        [XmlElement("LAC")]
        public string LAC { get; set; }

        [XmlElement("SCSCode")]
        public string SCSCode { get; set; }

        [XmlElement("ParentEmployerAccpacCode")]
        public string ParentEmployerAccpacCode { get; set; }
    }
}

Here is the code that does the serialization:

private void SaveToXML()
{
    try
    {
        XmlSerializer _serializer = new XmlSerializer(typeof(ObservableCollection<Code>));
        using (StreamWriter _writer = new StreamWriter(@"LocalCodes.xml"))
        {
            _serializer.Serialize(_writer, CodeCollection);
        }
    }
    catch (Exception ex)
    {

    }
}
Was it helpful?

Solution

This way you are trying to serialize an object of type ObservableCollection, soon will not have control of the name displayed in the xml tag. You need another class named Codes with a property that contains this collection and XmlElement attribute with parameter Code.

    var codes = new Codes { CodeCollection = codeCollection };
    XmlSerializer _serializer = new XmlSerializer(typeof(Codes));
    using (StreamWriter _writer = new StreamWriter(@"LocalCodes.xml"))
    {
        _serializer.Serialize(_writer, codes);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top