Để đọc và ghi file XML bằng ASP.NET, bạn có thể sử dụng lớp XmlDocument trong System.Xml namespace. Dưới đây là một ví dụ cơ bản:
Đọc file XML:
using System;
using System.Xml;
public class Program
{
public static void Main()
{
// Đường dẫn tới file XML
string filePath = "path_to_xml_file.xml";
// Tạo đối tượng XmlDocument
XmlDocument xmlDoc = new XmlDocument();
// Load file XML từ đường dẫn
xmlDoc.Load(filePath);
// Lấy danh sách các phần tử trong file XML
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("element_name");
// Duyệt qua danh sách các phần tử
foreach (XmlNode node in nodeList)
{
// Lấy giá trị của thuộc tính trong phần tử
string attributeValue = node.Attributes["attribute_name"].Value;
// Lấy nội dung của phần tử
string elementValue = node.InnerText;
Console.WriteLine("Attribute Value: " + attributeValue);
Console.WriteLine("Element Value: " + elementValue);
}
}
}
Ghi file XML:
using System;
using System.Xml;
public class Program
{
public static void Main()
{
// Tạo đối tượng XmlDocument
XmlDocument xmlDoc = new XmlDocument();
// Tạo phần tử gốc
XmlElement rootElement = xmlDoc.CreateElement("root");
xmlDoc.AppendChild(rootElement);
// Tạo phần tử con
XmlElement childElement = xmlDoc.CreateElement("child");
childElement.InnerText = "Hello World";
rootElement.AppendChild(childElement);
// Lưu file XML
string filePath = "path_to_save_xml_file.xml";
xmlDoc.Save(filePath);
Console.WriteLine("XML file saved successfully.");
}
}
Lưu ý thay đổi path_to_xml_file.xml và path_to_save_xml_file.xml thành đường dẫn tới file XML bạn muốn đọc và lưu.