|
XML hujjat hosil qilishning bir nechta usullarini ko'rib chiqamiz
|
bet | 79/175 | Sana | 16.05.2024 | Hajmi | 7,42 Mb. | | #237523 |
Bog'liq To\'plam WebXML hujjat hosil qilishning bir nechta usullarini ko'rib chiqamiz.
public class Talaba
{
public int Id { get; set; }
public string Ism { get; set; }
public string Familiya { get; set; }
public string TelNomer { get; set; }
15.2. XmlDocument va XmlNode sinflari yordamida ishlash.
XmlDocument sinfidan yangi obyekt hosil qilamiz:
XmlDocument document = new XmlDocument();
XmlNode sinfi orqali Xml hujjat parametrlarini hosil qilamiz va uni AppendChild metodi yordamida document ga qo'shamiz:
XmlNode xnode = document.CreateXmlDeclaration("1.0", "UTF-8", null);
document.AppendChild(xnode);
Xml da yangi element hosil qilish XmlNode sinfining CreateElement metodi, elementga qiymat berish uchun esa CreateTextNode metodidan foydalanamiz.
Talabalar nomli bosh elementni yaratamiz va uni documentga qo'shamiz:
XmlNode talabalar = document.CreateElement("Talabar");
document.AppendChild(talabalar);
Endi Talaba modelining xususiyatlarini element shaklida tashkil qilgan Talaba nomli element hosil qilamiz:
XmlNode talaba = document.CreateElement("Talaba");
talabalar.AppendChild(talaba);
XmlNode id = document.CreateElement("Id");
id.AppendChild(document.CreateTextNode("1"));
talaba.AppendChild(id);
XmlNode ism = document.CreateElement("Ism");
ism.AppendChild(document.CreateTextNode("Nodirbek"));
talaba.AppendChild(ism);
XmlNode familiya = document.CreateElement("Familiya");
familiya.AppendChild(document.CreateTextNode("Abdulaxadov"));
talaba.AppendChild(familiya);
XmlNode nomer = document.CreateElement("TelNomer");
nomer.AppendChild(document.CreateTextNode("+998901234567"));
talaba.AppendChild(nomer);
Yaratgan Xml hujjatimizni saqlaymiz:
document.Save("Talabalar.xml");
XmlWriter sinfining metodlaridan va yuqoridagi model va ketma-ketlikdan foydalanib yangi Talabalar.xml nomli hujjat hosil qilamiz.
XmlWriter sinfidan yangi obyekt hosil qilish uchun dastlab uning sozlamalarini hosil qilish kerak bo'ladi:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter obyektini Talabalar.xml fayli nomi va yuqoridagi settings bilan hosil qilamiz:
XmlWriter writer = XmlWriter.Create("Talabalar.xml", settings);
Talaba modelining xususiyatlarini kiritib, hujjatimizni hosil qilamiz:
writer.WriteStartDocument();
writer.WriteStartElement("Talabalar");
writer.WriteStartElement("Talaba");
writer.WriteStartElement("Id");
writer.WriteValue("1");
writer.WriteEndElement();
writer.WriteStartElement("Ism");
writer.WriteValue("Baxtiyor");
writer.WriteEndElement();
writer.WriteStartElement("Familiya");
writer.WriteValue("Murodov");
writer.WriteEndElement();
writer.WriteStartElement("TelNomer");
writer.WriteValue("+998901234567");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
|
| |