Search code examples
c#xmlserializer

How to deserialize XML with repeating tag name with unique identifier as attribute?


I am trying to deserialize this xml where all the node has the same name with a unique identifier as an attribute.

<configuration>
    <setting name="host">
        <value>127.0.0.1</value>
    </setting>
    <setting name="port">
        <value>80</value>
    </setting>
</configuration>

The result I am trying to achieve is:

public class Configuration
{
    string host { get; set; }
    int port { get; set; }
}

I read the previous question and I am still stumbling with the fact they have the same tag name.

Thank you!


Solution

  • Try this:

            XmlDocument doc = new XmlDocument();
            doc.LoadXml("yourxmlhere");
    
            Configuration configuration = new Configuration();
            XmlNode root = doc.FirstChild;
            if (root.HasChildNodes)
            {
                foreach (XmlNode item in root.ChildNodes)
                {
                    configuration = SetValueByPropertyName(configuration, item.Attributes["name"].Value, item.FirstChild.InnerText);
                }
            }
    

    The helper method to set values:

    public static TInput SetValueByPropertyName<TInput>(TInput obj, string name, string value)
            {
                PropertyInfo prop = obj.GetType().GetProperty(name);
                if (null != prop && prop.CanWrite)
                {
                    if (prop.PropertyType != typeof(String))
                    {
                        prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType), null);
                    }
                    else
                    {
                        prop.SetValue(obj, value, null);
                    }
                }
                return obj;
            }