निम्नलिखित कोड आपको XML से ऑब्जेक्ट्स में सामग्री लोड करने की अनुमति देगा। स्रोत, app.config या किसी अन्य फ़ाइल के आधार पर, उपयुक्त लोडर का उपयोग करें।
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");
}
}
फ़ाइल लोडर:
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;
}
}
}
}
धारा लोडर:
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;
}
}
डाटा परिभाषा:
[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; }
}
की ऐप की सामग्री।एक्सएमएल फ़ाइल के 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>
सामग्री:
<?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>
पोस्ट कोड विजुअल स्टूडियो 2010 (नेट 4.0) में चेक किया गया है। यह नेट 4.5.1 में काम करेंगे, तो आपके द्वारा दी गई नमूना बाहर डिबगर शुरू कर दिया है तो यह सबसे सरल निर्माता के साथ काम करेंगे तो
new XmlSerializer(typeof(School), null, null, null, null);
को
new XmlSerializer(typeof(School))
से seriliazer के निर्माण के बदलने के लिए, लेकिन शुरू कर दिया है, तो डीएसगिंग के साथ वीएस2013 आईडीई से, फिर कन्स्ट्रक्टर में बदलाव की आवश्यकता होगी या फिर FileNotFoundException होगा (कम से कम मेरे मामले में था)।
आप चयनित उत्तर क्यों नहीं चुनते? –