siguiente código le permitirá cargar contenido de XML en objetos. Según la fuente, app.config u otro archivo, use el cargador adecuado.
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Configuration;
using System.IO;
using System.Xml;
class Program
{
static void Main(string[] args)
{
var section = SectionSchool.Load();
var file = FileSchool.Load("School.xml");
}
}
cargador del archivo:
public class FileSchool
{
public static School Load(string path)
{
var encoding = System.Text.Encoding.UTF8;
var serializer = new XmlSerializer(typeof(School));
using (var stream = new StreamReader(path, encoding, false))
{
using (var reader = new XmlTextReader(stream))
{
return serializer.Deserialize(reader) as School;
}
}
}
}
Sección cargador:
public class SectionSchool : ConfigurationSection
{
public School Content { get; set; }
protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
{
var serializer = new XmlSerializer(typeof(School)); // works in 4.0
// var serializer = new XmlSerializer(type, null, null, null, null); // works in 4.5.1
Content = (Schoool)serializer.Deserialize(reader);
}
public static School Load()
{
// refresh section to make sure that it will load
ConfigurationManager.RefreshSection("School");
// will work only first time if not refreshed
var section = ConfigurationManager.GetSection("School") as SectionSchool;
if (section == null)
return null;
return section.Content;
}
}
definición de datos:
[XmlRoot("School")]
public class School
{
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlElement("Student")]
public List<Student> Students { get; set; }
}
[XmlRoot("Student")]
public class Student
{
[XmlAttribute("Index")]
public int Index { get; set; }
}
contenido de 'aplicación.config'
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="School" type="SectionSchool, ConsoleApplication1"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<School Name="RT">
<Student Index="1"></Student>
<Student />
<Student />
<Student />
<Student Index="2"/>
<Student />
<Student />
<Student Index="3"/>
<Student Index="4"/>
</School>
</configuration>
contenido del archivo XML:
<?xml version="1.0" encoding="utf-8" ?>
<School Name="RT">
<Student Index="1"></Student>
<Student />
<Student />
<Student />
<Student Index="2"/>
<Student />
<Student />
<Student Index="3"/>
<Student Index="4"/>
</School>
código publicado ha sido comprobado en Visual Studio 2010 (.Net 4.0). Se trabajará en .Net 4.5.1 si cambia construcción de seriliazer de
new XmlSerializer(typeof(School))
a
new XmlSerializer(typeof(School), null, null, null, null);
Si se proporciona la muestra se inicia depurador fuera después trabajará con el constructor más simple, sin embargo, si inició desde VS2013 IDE con depuración, se necesitará un cambio en el constructor o bien se producirá la excepción FileNotFoundException (al menos eso fue en mi caso).
¿por qué no elige la respuesta seleccionada? –