30. XmlWriter yordamida ob'ektni XML fayliga yozish uchun C# usulini yozing.
Javob:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
class Person {
public string Name { get; set; }
public int Age { get; set; }
}
class Program {
static void Main(string[] args) {
Person p = new Person { Name = "John Smith", Age = 42 };
SerializeToXmlFile
("person.xml", p);
}
static void SerializeToXmlFile(string filename, T obj) {
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlWriter writer = XmlWriter.Create(filename)) {
serializer.Serialize(writer, obj);
}
}
}
Ushbu dastur ism va yoshga ega Shaxs obyektini yaratadi va keyin XmlWriter yordamida ushbu ob'ektni "person.xml" deb nomlangan XML fayliga seriyalashtiradi. SerializeToXmlFile usuli fayl nomi va ob'ektni oladi va ob'ektni o'sha faylga XML serializatsiyasi sifatida yozadi.
E'tibor bering, Person klassi seriyali bo'lishi uchun [Serializable] atributi bilan belgilanishi yoki IXmlSerializable interfeysini amalga oshirishi kerak. Bu holda biz XmlSerializer sinfidan foydalanmoqdamiz, ya'ni Person sinfida parametrsiz konstruktor bo'lishi kerak.
31. XmlReader va XmlWriter yordamida XML fayliga ma'lumotlarni o'qish va yozish uchun C# dasturini amalga oshiring.
Javob:
C# tilida XmlReader va XmlWriter yordamida ma'lumotlarni XML fayliga o'qish uchun quyidagi amallarni bajarishingiz mumkin:
1. XmlReader obyektini ishga tushiring va kiritish faylini oching.
2. XmlWriter obyektini yarating va chiqish faylini oching.
3. XmlReader yordamida kirish faylidagi maʼlumotlarni oʻqish uchun hali ham maʼlumotlar bor ekan.
4. XmlWriter yordamida ma'lumotlarni chiqish fayliga yozing.
5. Kirish va chiqish fayllarini yoping.
Mana kod
using System.Xml;
class Program
{
static void Main(string[] args)
{
// Initialize the reader and writer objects
using (XmlReader reader = XmlReader.Create("inputfile.xml"))
using (XmlWriter writer = XmlWriter.Create("outputfile.xml"))
{
// Read data from the input file and write to the output file
while (reader.Read())
{
writer.WriteNode(reader, true);
}
}
}
}
Ushbu misolda biz "inputfile.xml" faylini o'qiymiz va "outputfile.xml" fayliga yozamiz. WriteNode usuli ma'lumotlarni o'quvchidan chiqish fayliga, shu jumladan har qanday tugunlar yoki atributlarga yozadi.
Do'stlaringiz bilan baham: |