I have an XML document:
<Preferences>
<Section Name="PREF_SECTION_NAME_1">
<Preference Name="PREF_NOTIFY" Type="radio">
<Options>
<Option Name="PREF_OPT_YES" Value="true"/>
<Option Name="PREF_OPT_NO" Value="false"/>
</Options>
<Default>true</Default>
</Preference>
<Preference Name="PREF_EXAMPLE" Type="textarea" >
<Default>lots and lots of lines of text"</Default>
</Preference>
</Section>
</Preferences>
This my Model:
[XmlRoot("Preferences")]
public class PreferencesModel
{
[XmlElement(ElementName = "Section")]
public List<Section> Section { get; set; }
}
public class Section
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlElement("Preference")]
public List<PreferenceModel> PreferenceModel { get; set; }
}
[XmlType("Preference")]
public class PreferenceModel
{
[XmlAttribute("Type")]
public string Type { get; set; }
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlAttribute("Default")]
public string Default { get; set; }
[XmlElement("Options")]
public List<Option> Options { get; set; }
}
[XmlAttribute("Name")]
[XmlType("Option")]
public class Option
{
public string Name { get; set; }
[XmlAttribute("Value")]
public string Value { get; set; }
}
I use XDocument to make this XML data accessible via Linq:
My Method to XML to Model:
public PreferencesModel GetDefaults(XmlDocument userDoc)
{
XDocument xDocUser = userDoc.ToXDocument();
return new PreferencesModel()
{
Section = xDocUser.Root.Elements("Section").Select(x => new Section()
{
Name = x.Attribute("Name").Value,
PreferenceModel = x.Elements("Preference").Select(
y => new PreferenceModel()
{
Name = y.Attribute("Name").Value,
Default = (string)y.Element("Default").Value,
Type = y.Attribute("Type").Value,
Options = y.Elements("Options").Select(z => new Option()
{
Name = z.Attribute("Name").Value,
Value = z.Attribute("Value").Value
}).ToList(),
}).ToList(),
}).ToList()
};
}
and when i run I get this:
