XML là ngôn ngữ tự mô tả, cung cấp cả dữ liệu và quy tắc xác định thông tin chứa đựng. Giống HTML, XML là tập con của SGML (Standard Generalized Markup Language).
Lớp XDocument chứa thông tin cần thiết cho một XML document hợp lệ. Bao gồm XML declaration, processing instructions, và comments.
Chỉ tạo XDocument objects khi cần chức năng cụ thể của lớp này. Nhiều trường hợp có thể làm việc trực tiếp với XElement - mô hình lập trình đơn giản hơn.
XDocument kế thừa từ XContainer, do đó có thể chứa child nodes. Tuy nhiên, XDocument objects chỉ có thể có một child XElement node. Điều này phản ánh chuẩn XML: chỉ có một root element trong XML document. XDocument nằm trong namespace System.Xml.Linq.
Ví dụ
Xét string dưới dạng XML cần chuyển thành XDocument:
<Departments>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
</Departments>
using System;
using System.Xml.Linq;
namespace DemoApplication
{
public class Program
{
public static void Main()
{
string xmlString = @"<Departments>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
</Departments>";
XDocument xml = XDocument.Parse(xmlString);
Console.ReadLine();
}
}
}
Tương tự, nếu muốn chuyển file chứa XML thành XDocument, dùng XDocument.Load(path).
Ví dụ
using System;
using System.Xml.Linq;
namespace DemoApplication
{
public class Program
{
public static void Main()
{
string xmlPath = @"D:\DemoXml.txt";
XDocument xml = XDocument.Load(xmlPath);
Console.ReadLine();
}
}
}
Kết quả
Trong cả hai trường hợp, xmlString được chuyển thành XDocument như sau:
