Search code examples
c#xmlclassdeserialization

C# : Deserialize xml with an unknow number of attributes


I would like to deserialize xml files with the following pattern : enter image description here

I would like to put the data into a class call Parameter. However, as you can see, I don't knwo by advance how many <Device> I get between <Parameters> ... </Parameters> and the deserialization is not possible with such a DeserializeObjectXMLFile method.

public static Parameters DeserializeObjectXMLFile(String fileToRead)
        {
            try
            {
                Parameters parameters = null;
                XmlSerializer xs = new XmlSerializer(typeof(Parameters));
                
                using (StreamReader sr = new StreamReader(fileToRead))
                {
                    parameters = xs.Deserialize(sr) as Parameters;
                }
                
                return parameters;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);

                throw ex;

            }
        }

I imagined having a property List<Device> Devices {get; set} in my Parameters class but deserialization won't work and I don't know how I can do it.

Could you help me in finding a solution ?

Best regards.

Rémi


Solution

  • Use the XmlDocument object in the System.Xml namespace to parse the XML instead of serializing it.

    Here is an example:

    var xDoc = new System.Xml.XmlDocument();
    xDoc.Load(pathToXml);
    
    foreach (System.Xml.XmlNode node in xDoc.DocumentElement.ChildNodes) 
    {
         var attrName = node.Attributes[0].Name;
         var attrValue = node.Attributes[0].Value;
         Device dev = new Device(attrName, attrValue);
         deviceList.Add(dev);
    }
    

    While parsing you can then create a new instance of Parameters and add it to a List object.