Adrian Serafin
Adrian Serafin

Reputation: 7715

Problem with C# XmlSerialization

I have xml file:

<?xml version="1.0" encoding="utf-8"?>
<LabelTypesCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance="xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <LabelTypes>    
    <LabelType>
      <Name>LabelTypeProduct</Name>
    </LabelType>
    <LabelType>
      <Name>LabelTypeClient</Name>
    </LabelType>    
  </LabelTypes>
</LabelTypesCollection>

And 2 c# classes:

[Serializable]
[XmlRoot("LabelTypesCollection")]
public class LabelTypesCollection
{
    private static string _labelTypesCollectionPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.Combine(Program.ProgramName, "LabelTypesCollection.xml"));

    [XmlArray("LabelTypes", ElementName="LabelType")]
    public List<LabelType> LabelTypes { get; set; }

    public static LabelTypesCollection LoadAllLabelTypes()
    {
        FileInfo fi = new FileInfo(_labelTypesCollectionPath);
        if (!fi.Exists)
        {
            Logger.WriteLog("Could not find size_types_collection.xml file.", new Exception("Could not find size_types_collection.xml file."));
            return new LabelTypesCollection();
        }

        try
        {
            using (FileStream fs = fi.OpenRead())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(LabelTypesCollection));
                LabelTypesCollection labelTypesCollection = (LabelTypesCollection)serializer.Deserialize(fs);
                return labelTypesCollection;
            }
        }
        catch (Exception ex)
        {
            Logger.WriteLog("Error during loading LabelTypesCollection", ex);
            return null;
        }
    }
}


[Serializable]    
public class LabelType
{
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlIgnore]
    public string TranslatedName
    {
        get
        {
            string translated = Common.Resources.GetValue(Name);
            return (translated == null) ? Name : translated;
        }
    }
}

And when I call:

LabelTypesCollection.LoadAllLabelTypes();

I get LabelTypeCollection object with empty LabelTypes list. There is no error or anything. Could anyone point me to the problem?

Upvotes: 1

Views: 1005

Answers (3)

AakashM
AakashM

Reputation: 63338

Change this

[XmlArray("LabelTypes", ElementName="LabelType")]

to this

[XmlArray]

The ElementName of an XmlArrayAttribute specifies the element name of the container, and is actually what you specify in the first parameter to the ctor! So the ctor you have says "this class serializes as a container named LabelTypes; no wait actually I want the container to be named LabelType". The named parameter is overwriting what the first unnamed parameter says.

And in fact, since you want the container element to be named LabelTypes, which is what the member is actually called, you don't need to specify it at all.

You may have been thinking of XmlArrayItemAttribute, which controls what the individual members of a serialized collection are named - but you don't need that here either.

My usual approach for working out xml serializer stuff is to build objects manually then look at the xml they serialize to. In this case, using the code you currently have produces xml like this:

<?xml version="1.0" encoding="utf-16"?>
<LabelTypesCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <LabelType>
    <LabelType>
      <Name>one</Name>
    </LabelType>
    <LabelType>
      <Name>two</Name>
    </LabelType>
  </LabelType>
</LabelTypesCollection>

which is what tipped me off to the incorrect LabelType specifier.

Note that you also don't need the XmlRoot on LabelTypesCollection, or the XmlElement on Name, since you are just specifying what the xml serializer will come up with anyway.

Upvotes: 2

Ran
Ran

Reputation: 6159

Here's a suggestion.

Write a small test program that creates an instance of LabelTypesCollection, and adds some LabelType objects into it.

Then use an XmlSerializer to write the object to a file, and look at the Xml you get, to ensure that your input Xml is in the correct schema.

Maybe there's something wrong with one of your Xml elements.

Upvotes: 2

Pabuc
Pabuc

Reputation: 5638

I really think you get an empty list because your code can't find the xml file. Also try instantiating your list. If you have the xml path correctly.

public List<LabelType> LabelTypes = new List<LabelType>();

Upvotes: 0

Related Questions