SlideShare a Scribd company logo
LINQ TO XML


Contents




                1
1. Giới thiệu LINQ to XML:
LINQ to XML cung cấp một giao diện lập trình XML.

LINQ to XML sử dụng những ngôn ngữ mới nhất của .NET Language Framework và
được nâng cấp, thiết kế lại với giao diện lập trình XML Document Object Model (DOM).

XML đã được sử dụng rộng rãi để định dạng dữ liệu trong một loạt các ngữ cảnh (các
trang web, trong các tập tin cấu hình, trong các tập tin Microsoft Office Word, và trong
cơ sở dữ liệu).


LINQ to XML có cấu trúc truy vấn tương tự SQL. Nhà phát triển trung bình có thể viết
các truy vấn ngắn gọn, mạnh mẽ, viết mã ít hơn nhưng có ý nghĩa nhiều hơn. Họ có thể
sử dụng các biểu thức truy vấn từ nhiều dữ liệu các lĩnh vực tại một thời điểm.

LINQ to XML cũng giống như Document Object Model (DOM) ở chỗ nó chuyển các tài
liệu XML vào bộ nhớ. Bạn có thể truy vấn và sửa đổi các tài liệu, và sau khi bạn chỉnh
sửa nó, bạn có thể lưu nó vào một tập tin hoặc xuất nó ra. Tuy nhiên, LINQ to XML khác
DOM: Nó cung cấp mô hình đối tượng mới đơn giản hơn và dễ thao tác hơn để làm việc ,
và đó là tận dụng các cải tiến ngôn ngữ trong Visual C # 2008.


Khả năng sử dụng kết quả truy vấn là tham số cho đối tượng XElement và XAttribute cho
phép một phương pháp mạnh mẽ để tạo ra cây XML. Phương pháp này, được gọi là
functional construction, cho phép các nhà phát triển để dễ dàng chuyển đổi cây XML từ một

hình dạng này sang hình dạng khác.

Sử dụng LINQ to XML bạn có thể:

      • Load XML từ nhiều file hoặc luồng.

      • Xuất XML ra file hoặc luồng.

      • Truy vấn cây XML bằng những truy vấn LINQ.

      • Thao tác cây XML trong bộ nhớ.

      • Biến đổi cây XML từ dạng này sang dạng khác.



                                            2
2. Xây dựng một cây XML bằng Visual C# 2008:
   2.1.Tạo một phần tử XML:

Cấu trúc
XElement(XName name, object content)

XElement(XName name)
XName: tên phần tử.

object: nội dụng của phần tử.


Ví dụ sau tạo phần tử <Customer>có nội dung “Adventure Works”.

C#
XElement        n     =   new      XElement("Customer",   "Adventure
Works");

Console.WriteLine(n);

Xml
<Customer>Adventure Works</Customer>


Tạo phần tử rỗng để trống phân nội dung:

C#
XElement n = new XElement("Customer");

Console.WriteLine(n);

Xml
<Customer />


   2.2.Tạo một thuộc tính cho phần tử XML:


                                           3
Cấu trúc
XAttribute(XName name, object content)
Tham số:

XName: thuộc tính.

object: giá trị của thuộc tính.



C#
XElement phone = new XElement("Phone",
    new XAttribute("Type", "Home"),
    "555-555-5555");
Console.WriteLine(phone);


Xml
<Phone Type="Home">555-555-5555</Phone>




                                  4
2.3.Tạo ghi chú trong cây XML:
Tạo một phần tử gồm một chú thích như một nút con

Tên
XComment(String)


C#
XElement root = new XElement("Root",
    new XComment("This is a comment")
);
Console.WriteLine(root);


Xml
<Root>
  <!--This is a comment-->
</Root>




                                         5
2.4.Xây dựng một cây XML:
Sử dụng đối tượng XDocument xây dựng một cây XML. Thông thường ta có thể tạo ra
cây XML với nút gốc XElement.

Name                           Description

XDocument()                    Initializes a new instance of the
                               XDocument class.

XDocument(Object[])            Initializes a new instance of the
                               XDocument class with the specified
                               content.

XDocument(XDocument)           Initializes a new instance of the
                               XDocument class from an existing
                               XDocument object.

XDocument(XDeclaration,        Initializes a new instance of the
Object[])                      XDocument class with the specified
                               XDeclaration and content.



C#
XDocument doc = new XDocument(
    new XComment("This is a comment"),
    new XElement("Root",
        new XElement("Info5", "info5"),
        new XElement("Info6", "info6"),
        new XElement("Info7", "info7"),
        new XElement("Info8", "info8")
    )
);
Console.WriteLine(doc);

Xml
<!--This is a comment-->
<Root>
  <Child1>data1</Child1>

                                       6
<Child2>data2</Child2>
  <Child3>data3</Child3>
  <Child2>data4</Child2>
</Root>




                           7
2.5.Đối tượng XDeclaration:
Đối tượng XDeclaration được sử dụng để khai báo XML version, encoding, and có thể có
hoặc không thuộc tính standalone của một tài liệu XML.



Cấu trúc
XDeclaration(string version,string encoding,string standalone)



C#
XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XComment("This is a comment"),
    new XElement("Root", "content")
);
doc.Save("Root.xml");

Console.WriteLine(File.ReadAllText("Root.xml"));


Xml
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--This is a comment-->
<Root>content</Root>




                                         8
2.6.Phương thức XElement.Save:

Name                Description
Save(String)        Serialize this element to a file.


C#
XElement root = new XElement("Root",
    new XElement("Child", "child content")
);
root.Save("Root.xml");
string str = File.ReadAllText("Root.xml");
Console.WriteLine(str);


Xml
<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Child>child content</Child>
</Root>




                                    9
2.7.Phương thức XDocument.Save:

Name               Description
Save(String)       Serialize this XDocument to a file.



C#
XDocument doc = new XDocument(
    new XElement("Root",
        new XElement("Child", "content")
    )
);
doc.Save("Root.xml");
Console.WriteLine(File.ReadAllText("Root.xml"));

Xml
<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Child>content</Child>
</Root>




                                         10
2.8.Phương thức XElement.Load:

Name               Description
Load(String)       Loads an XElement from a file.



C#
XElement xmlTree1 = new XElement("Root",
    new XElement("Child", "content")
);
xmlTree1.Save("Tree.xml");

XElement xmlTree2 = XElement.Load("Tree.xml");
Console.WriteLine(xmlTree2);



<Root>
  <Child>content</Child>
</Root>




                                       11
2.9.Phương thức XDocument.Load:

Name           Description
Load(String)   Creates a new XDocument from a file.


C#
XElement xmlTree1 = new XElement("Root",
    new XElement("Child", "content")
);
xmlTree1.Save("Tree.xml");

XDocument xmlTree2 = XDocument.Load("Tree.xml");
Console.WriteLine(xmlTree2);


Xml
<Root>
  <Child>content</Child>
</Root>




                                    12
3. XML namespace:
   3.1.Giới thiệu namespace:
XML namespace giúp tránh xung đột giửa các bộ phận khác nhau của một tài liệu XML.
khi khai báo một namespace, bạn chọn một tên cục bộ sao cho nó là duy nhất.

Những tiền tố làm cho tài liệu XML súc tích và dễ hiểu hơn.

Một trong những lợi thế khi sử dụng LINQ to XML với C# là đơn giản hóa những XML
name là loại bỏ những thủ tục mà những nhà phát triễn sử dụng tiền tố. khi LINQ load
hoặc parse một tài liệu XML, mỗi tiền tố sẽ được xử lý để phù hợp với namespace XML.
khi làm việc với tài liệu có namespace, bạn thường truy cập namespace thông qua
namespace URI, không thông qua tiền tố namespace.




                                          13
3.2.Tạo một namespace trong cây XML:
Xem ví dụ sau:

C#                      Copy Code
// Create an XML tree in a namespace, with a specified
prefix
XNamespace aw = "http://www.adventure-works.com";
XElement root = new XElement(aw + "Root",
           new   XAttribute(XNamespace.Xmlns  +   "aw",
"http://www.adventure-works.com"),
    new XElement(aw + "Child", "child content")
);
Console.WriteLine(root);

Xml
<aw:Root xmlns:aw="http://www.adventure-works.com">
  <aw:Child>child content</aw:Child>
</aw:Root>




                                    14
3.3.Điều khiển tiền tố namespace trong cây XML:
Ví dụ sau khai báo hai tiền tố namespace. Tên miền   http://www.adventure-works.com   có
tiền tố aw, và www.fourthcoffee.com có tiền tố fc.

C#
XNamespace aw = "http://www.adventure-works.com";
XNamespace fc = "www.fourthcoffee.com";
XElement root = new XElement(aw + "Root",
           new   XAttribute(XNamespace.Xmlns   +  "aw",
"http://www.adventure-works.com"),
           new   XAttribute(XNamespace.Xmlns   +  "fc",
"www.fourthcoffee.com"),
    new XElement(fc + "Child",
           new XElement(aw + "DifferentChild", "other
content")
    ),
    new XElement(aw + "Child2", "c2 content"),
    new XElement(fc + "Child3", "c3 content")
);
Console.WriteLine(root);

Xml
<aw:Root      xmlns:aw="http://www.adventure-works.com"
xmlns:fc="www.fourthcoffee.com">
  <fc:Child>
                               <aw:DifferentChild>other
content</aw:DifferentChild>
  </fc:Child>
  <aw:Child2>c2 content</aw:Child2>
  <fc:Child3>c3 content</fc:Child3>
</aw:Root>




                                        15
3.4.Viết truy vấn LINQ trong namespace:
Xem ví dụ sau:

C#
XNamespace aw = "http://www.adventure-works.com";
XElement root = XElement.Parse(
@"<Root xmlns='http://www.adventure-works.com'>
    <Child>1</Child>
    <Child>2</Child>
    <Child>3</Child>
    <AnotherChild>4</AnotherChild>
    <AnotherChild>5</AnotherChild>
    <AnotherChild>6</AnotherChild>
</Root>");
IEnumerable<XElement> c1 =
    from el in root.Elements(aw + "Child")
    select el;
foreach (XElement el in c1)
    Console.WriteLine((int)el);



1
2
3




                                      16
4. Những thao tác truy vấn cơ bản trên cây XML:
   4.1.Tìm một phần tử trong cây XML:
Xét ví dụ sau tìm phần tử Address có thuộc tính Type có giá trị là "Billing".

C#
XElement root = XElement.Load("PurchaseOrder.xml");

IEnumerable<XElement> address =

      from el in root.Elements("Address")

      where (string)el.Attribute("Type") == "Billing"

      select el;

foreach (XElement el in address)

      Console.WriteLine(el);




Xml
<Address Type="Billing">

   <Name>Tai Yee</Name>

   <Street>8 Oak Avenue</Street>

   <City>Old Town</City>

   <State>PA</State>

   <Zip>95819</Zip>

   <Country>USA</Country>



                                          17
</Address>




             18
4.2.Lọc phần tử trong cây XML:
Ví dụ sau lọc những phần tử có phần tử con <Type > có Value="Yes".

C#
XElement root = XElement.Parse(@"<Root>
  <Child1>
    <Text>Child One Text</Text>
    <Type Value=""Yes""/>
  </Child1>
  <Child2>
    <Text>Child Two Text</Text>
    <Type Value=""Yes""/>
  </Child2>
  <Child3>
    <Text>Child Three Text</Text>
    <Type Value=""No""/>
  </Child3>
  <Child4>
    <Text>Child Four Text</Text>
    <Type Value=""Yes""/>
  </Child4>
  <Child5>
    <Text>Child Five Text</Text>
  </Child5>
</Root>");
var cList =
                          from      typeElement      in
root.Elements().Elements("Type")
       where (string)typeElement.Attribute("Value") ==
"Yes"
    select (string)typeElement.Parent.Element("Text");
foreach(string str in cList)
    Console.WriteLine(str);




Child One Text


                                     19
Child Two Text
Child Four Text




                  20
4.3.Sắp xếp các phần tử trong cây XML:

C#
XElement root = XElement.Load("Data.xml");
IEnumerable<decimal> prices =
    from el in root.Elements("Data")
    let price = (decimal)el.Element("Price")
    orderby price
    select price;
foreach (decimal el in prices)
    Console.WriteLine(el);




0.99
4.95
6.99
24.50
29.00
66.00
89.99




                                    21
4.4.Kết hai cây XML:
Ví dụ sau kết những phần tử Customer với những phần tử Order , và tạo ra tài liệu XML
mới gồm phần tử CompanyName bên trong order.

C#
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", "CustomersOrders.xsd");

Console.Write("Attempting to validate, ");
XDocument                  custOrdDoc                                             =
XDocument.Load("CustomersOrders.xml");

bool errors = false;
custOrdDoc.Validate(schemas, (o, e) =>
                     {
                                Console.WriteLine("{0}",
e.Message);
                          errors = true;
                     });
Console.WriteLine("custOrdDoc {0}", errors ? "did not
validate" : "validated");

if (!errors)
{
    // Join customers and orders, and create a new XML
document with
    // a different shape.

       // The new document contains orders only for
customers with a
    // CustomerID > 'K'
    XElement custOrd = custOrdDoc.Element("Root");
    XElement newCustOrd = new XElement("Root",
                                      from     c   in
custOrd.Element("Customers").Elements("Customer")
                                      join     o   in
custOrd.Element("Orders").Elements("Order")


                                         22
on (string)c.Attribute("CustomerID")
equals
                      (string)o.Element("CustomerID")
                                                  where
((string)c.Attribute("CustomerID")).CompareTo("K") > 0
        select new XElement("Order",
                            new XElement("CustomerID",
(string)c.Attribute("CustomerID")),
                           new XElement("CompanyName",
(string)c.Element("CompanyName")),
                           new XElement("ContactName",
(string)c.Element("ContactName")),
                            new XElement("EmployeeID",
(string)o.Element("EmployeeID")),
                             new XElement("OrderDate",
(DateTime)o.Element("OrderDate"))
        )
    );
    Console.WriteLine(newCustOrd);
}


Attempting to validate, custOrdDoc validated
<Root>
  <Order>
    <CustomerID>LAZYK</CustomerID>
    <CompanyName>Lazy K Kountry Store</CompanyName>
    <ContactName>John Steel</ContactName>
    <EmployeeID>1</EmployeeID>
    <OrderDate>1997-03-21T00:00:00</OrderDate>
  </Order>
  <Order>
    <CustomerID>LAZYK</CustomerID>
    <CompanyName>Lazy K Kountry Store</CompanyName>
    <ContactName>John Steel</ContactName>
    <EmployeeID>8</EmployeeID>
    <OrderDate>1997-05-22T00:00:00</OrderDate>
  </Order>
  <Order>
    <CustomerID>LETSS</CustomerID>


                           23
<CompanyName>Let's Stop N Shop</CompanyName>
    <ContactName>Jaime Yorres</ContactName>
    <EmployeeID>1</EmployeeID>
    <OrderDate>1997-06-25T00:00:00</OrderDate>
  </Order>
  <Order>
    <CustomerID>LETSS</CustomerID>
    <CompanyName>Let's Stop N Shop</CompanyName>
    <ContactName>Jaime Yorres</ContactName>
    <EmployeeID>8</EmployeeID>
    <OrderDate>1997-10-27T00:00:00</OrderDate>
  </Order>
  <Order>
    <CustomerID>LETSS</CustomerID>
    <CompanyName>Let's Stop N Shop</CompanyName>
    <ContactName>Jaime Yorres</ContactName>
    <EmployeeID>6</EmployeeID>
    <OrderDate>1997-11-10T00:00:00</OrderDate>
  </Order>
  <Order>
    <CustomerID>LETSS</CustomerID>
    <CompanyName>Let's Stop N Shop</CompanyName>
    <ContactName>Jaime Yorres</ContactName>
    <EmployeeID>4</EmployeeID>
    <OrderDate>1998-02-12T00:00:00</OrderDate>
  </Order>
</Root>




                           24
4.5.Nhóm các phần tử trong một cây XML:
Ví dụ nhóm dữ liệu theo loại, sau đó tạo ra một tập tin XML mới, trong đó phân cấp
XML theo nhóm.

C#
XElement doc = XElement.Load("Data.xml");

var newData =

      new XElement("Root",

           from data in doc.Elements("Data")

         group data by (string)data.Element("Category")
into groupedData

           select new XElement("Group",

                 new XAttribute("ID", groupedData.Key),

                 from g in groupedData

                 select new XElement("Data",

                       g.Element("Quantity"),

                       g.Element("Price")

                 )

           )

      );

Console.WriteLine(newData);

Xml
<Root>

  <Group ID="A">


                                       25
<Data>

    <Quantity>3</Quantity>

    <Price>24.50</Price>

  </Data>

  <Data>

    <Quantity>5</Quantity>

    <Price>4.95</Price>

  </Data>

  <Data>

    <Quantity>3</Quantity>

    <Price>66.00</Price>

  </Data>

  <Data>

    <Quantity>15</Quantity>

    <Price>29.00</Price>

  </Data>

</Group>

<Group ID="B">

  <Data>

    <Quantity>1</Quantity>

    <Price>89.99</Price>

  </Data>




                           26
<Data>

      <Quantity>10</Quantity>

      <Price>.99</Price>

    </Data>

    <Data>

      <Quantity>8</Quantity>

      <Price>6.99</Price>

    </Data>

  </Group>

</Root>




                            27
5. Những thao tác biến đổi trên cây XML:
     5.1.Thêm phần tử, thuộc tính và nút vào một cây XML:
Thêm nút vào cuối cây hoặc đầu cây dùng phương thức .Add và .AddFirst .

C#
XElement xmlTree = new XElement("Root",

       new XElement("Child1", 1),

       new XElement("Child2", 2),

       new XElement("Child3", 3),

       new XElement("Child4", 4),

       new XElement("Child5", 5)

);

xmlTree.Add(new XElement("NewChild", "new content"));

Console.WriteLine(xmlTree);



<Root>

  <Child1>1</Child1>

  <Child2>2</Child2>

  <Child3>3</Child3>

  <Child4>4</Child4>

  <Child5>5</Child5>

  <NewChild>new content</NewChild>




                                        28
</Root>




          29
5.2.Thay đổi phần tử, thuộc tính và nút của một cây XML:
Sử dụng phương thức XAttribute.SetValue thay đổi giá trị thuộc tính "Att" từ"root"
thành"new content".

C#
XElement root = new XElement("Root",
    new XAttribute("Att", "root"),
    (“Root”)
);
Console.WriteLine(root);
Console.WriteLine(“---------------”)
XAttribute att = root.Attribute("Att");
att.SetValue("new content");
root.SetValue("new content");
Console.WriteLine(root);


<Root Att="root">Root</Root>
<-------------->
<Root Att="new content">new content</Root>


Sử dụng phương thức XNode.ReplaceWith thay đổi nút có tên "Child3"có nội dung
"child3 content" thành "NewChild" nội dung "new content" .

C#
XElement xmlTree = new XElement("Root",
    new XElement("Child1", "child1 content"),
    new XElement("Child2", "child2 content"),
    new XElement("Child3", "child3 content"),
    new XElement("Child4", "child4 content"),
    new XElement("Child5", "child5 content")
);
XElement child3 = xmlTree.Element("Child3");
child3.ReplaceWith(
    new XElement("NewChild", "new content")
);


                                       30
Console.WriteLine(xmlTree);
Xml
<Root>
  <Child1>child1 content</Child1>
  <Child2>child2 content</Child2>
  <NewChild>new content</NewChild>
  <Child4>child4 content</Child4>
  <Child5>child5 content</Child5>
</Root>


Thiết lập giá trị của lớp con bằng hàm XElement.SetElementValue.

C#
// Create an element with no content
XElement root = new XElement("Root");

// Add some name/value pairs.
root.SetElementValue("Ele1", 1);
root.SetElementValue("Ele2", 2);
root.SetElementValue("Ele3", 3);
Console.WriteLine(root);

// Modify one of the name/value pairs.
root.SetElementValue("Ele2", 22);
Console.WriteLine(root);

// Remove one of the name/value pairs.
root.SetElementValue("Ele3", null);
Console.WriteLine(root);



<Root>
  <Ele1>1</Ele1>
  <Ele2>2</Ele2>
  <Ele3>3</Ele3>
</Root>
<Root>


                                         31
<Ele1>1</Ele1>
  <Ele2>22</Ele2>
  <Ele3>3</Ele3>
</Root>
<Root>
  <Ele1>1</Ele1>
  <Ele2>22</Ele2>
</Root>




                    32
5.3.Xóa phần tử, thuộc tính và nút từ một cây XML:
Ví dụ sau dùng phương thức XElement.RemoveAll xóa những phần tử con và thuộc tính của một
cây XML

C#
XElement root = new XElement("Root",
    new XAttribute("Att1", 1),
    new XAttribute("Att2", 2),
    new XAttribute("Att3", 3),
    new XElement("Child1", 1),
    new XElement("Child2", 2),
    new XElement("Child3", 3)
);
root.RemoveAll();    // removes children elements and
attributes of root
Console.WriteLine(root);


Xml
<Root />


Ví dụ tiếp theo dùng phương thức XElement.RemoveAttributes xóa toàn bộ thuộc tính của một
cây XML.

C#
XElement root = new XElement("Root",
    new XAttribute("Att1", 1),
    new XAttribute("Att2", 2),
    new XAttribute("Att3", 3),
    new XElement("Child1", 1),
    new XElement("Child2", 2),
    new XElement("Child3", 3)
);
root.RemoveAttributes();
Console.WriteLine(root);
Xml


                                           33
<Root>
  <Child1>1</Child1>
  <Child2>2</Child2>
  <Child3>3</Child3>
</Root>




Dùng phương thức XNode.Remove xóa một nút của cây XML

C#
XElement xmlTree = new XElement("Root",
    new XElement("Child1", "child1 content"),
    new XElement("Child2", "child2 content"),
    new XElement("Child3", "child3 content"),
    new XElement("Child4", "child4 content"),
    new XElement("Child5", "child5 content")
);
XElement child3 = xmlTree.Element("Child3");
child3.Remove();
Console.WriteLine(xmlTree);
Xml
<Root>
  <Child1>child1         content</Child1>
  <Child2>child2         content</Child2>
  <Child4>child4         content</Child4>
  <Child5>child5         content</Child5>
</Root>




                                        34

More Related Content

What's hot (20)

DOCX
Báo cáo đồ án môn công nghệ phần mềm
RiTa15
 
DOCX
Đề cương thông tin địa lý GIS
Ngô Doãn Tình
 
DOCX
Khái niệm thông tin và dữ liệu
minhhai07b08
 
PDF
Bao cao do an Phát triển hệ thống game server Online
Hoàng Phạm
 
DOCX
Bài tiểu luận Kỹ năng thuyết trình - Học viện công nghệ bưu chính viễn thông
Huyen Pham
 
PDF
Phân tích thiết kế hệ thống thông tin
huynhle1990
 
DOC
đồ áN phân tích thiết kế hệ thống quản lý bán hàng siêu thị
Thanh Hoa
 
PDF
Lập trình web asp.net MVC
MasterCode.vn
 
PDF
Đề tài: Xây dựng phần mềm quản lý nhà hàng ăn uống
Dịch Vụ Viết Thuê Khóa Luận Zalo/Telegram 0917193864
 
PDF
Đề tài: Chương trình quản lý nhân sự tiền lương tại doanh nghiệp
Dịch vụ viết bài trọn gói ZALO: 0909232620
 
DOCX
Hệ thống quản lý mua hàng siêu thị mini
Han Nguyen
 
PDF
Báo cáo đồ án tôt nghiệp: Xây dựng Website bán hàng thông minh
nataliej4
 
DOCX
Báo cáo phân tích thiết kế đồ án game
Tạ Thành Đạt
 
DOC
Tailieu.vncty.com huong dan nhap mon html
Trần Đức Anh
 
PDF
đồ áN xây dựng website bán laptop 1129155
nataliej4
 
PDF
Đệ Quy, Quay Lui, Nhánh Cận
Nguyễn Quang Thiện
 
DOCX
Báo Cáo Đồ Án Phần Mềm Quản lý chuỗi bất động sản FULL
TuanNguyen520568
 
PPT
C2.phan tich cong viec
Học Huỳnh Bá
 
PPTX
Slide Đồ Án Tốt Nghiệp Khoa CNTT Web Xem Phim Online Mới
Hiệu Nguyễn
 
PDF
Bảng tiêu chí đánh giá bài thuyết trình
Diệu Linh
 
Báo cáo đồ án môn công nghệ phần mềm
RiTa15
 
Đề cương thông tin địa lý GIS
Ngô Doãn Tình
 
Khái niệm thông tin và dữ liệu
minhhai07b08
 
Bao cao do an Phát triển hệ thống game server Online
Hoàng Phạm
 
Bài tiểu luận Kỹ năng thuyết trình - Học viện công nghệ bưu chính viễn thông
Huyen Pham
 
Phân tích thiết kế hệ thống thông tin
huynhle1990
 
đồ áN phân tích thiết kế hệ thống quản lý bán hàng siêu thị
Thanh Hoa
 
Lập trình web asp.net MVC
MasterCode.vn
 
Đề tài: Xây dựng phần mềm quản lý nhà hàng ăn uống
Dịch Vụ Viết Thuê Khóa Luận Zalo/Telegram 0917193864
 
Đề tài: Chương trình quản lý nhân sự tiền lương tại doanh nghiệp
Dịch vụ viết bài trọn gói ZALO: 0909232620
 
Hệ thống quản lý mua hàng siêu thị mini
Han Nguyen
 
Báo cáo đồ án tôt nghiệp: Xây dựng Website bán hàng thông minh
nataliej4
 
Báo cáo phân tích thiết kế đồ án game
Tạ Thành Đạt
 
Tailieu.vncty.com huong dan nhap mon html
Trần Đức Anh
 
đồ áN xây dựng website bán laptop 1129155
nataliej4
 
Đệ Quy, Quay Lui, Nhánh Cận
Nguyễn Quang Thiện
 
Báo Cáo Đồ Án Phần Mềm Quản lý chuỗi bất động sản FULL
TuanNguyen520568
 
C2.phan tich cong viec
Học Huỳnh Bá
 
Slide Đồ Án Tốt Nghiệp Khoa CNTT Web Xem Phim Online Mới
Hiệu Nguyễn
 
Bảng tiêu chí đánh giá bài thuyết trình
Diệu Linh
 

Viewers also liked (7)

PPT
Efs
Industech
 
PPTX
LINQ TO XML
biendltb
 
PDF
Cơ bản về XML cho người mới sử dụng
Duy Lê Văn
 
PDF
Tai lieu-xml
anhcubin
 
PDF
template magento
dvms
 
DOCX
Tỷ lệ vàng - một phát hiện vĩ đại của hình học
Bình Trọng Án
 
PDF
Luyện dịch Việt Anh
Bình Trọng Án
 
LINQ TO XML
biendltb
 
Cơ bản về XML cho người mới sử dụng
Duy Lê Văn
 
Tai lieu-xml
anhcubin
 
template magento
dvms
 
Tỷ lệ vàng - một phát hiện vĩ đại của hình học
Bình Trọng Án
 
Luyện dịch Việt Anh
Bình Trọng Án
 
Ad

Similar to LinQ to XML (20)

PDF
Hướng dẫn lập trình quản lý c#
An Nguyen
 
PDF
2_Giới thiệu và tạo file dữ liệu dưới dạngXML.pdf
PhamThiThuThuy1
 
PPTX
Lesson 19.xml
Hallo Patidu
 
PDF
Xml
xeroxk
 
PDF
Tailieu.vncty.com co ban ve xml
Trần Đức Anh
 
PPT
Thiết kế dữ liệu
Nguyen Tran
 
PDF
Căn bản về xml
Hieu Meteor
 
PPT
Chapter 4 xml schema
Bình Trọng Án
 
ODP
Android Nâng cao-Bài 8-JSON & XML Parsing
Phuoc Nguyen
 
PPT
hoc ve xml
mrtom16071980
 
DOC
Luận Văn Tích Hợp Csdl Quan Hệ Xml.doc
tcoco3199
 
PDF
07 x query
Ha Ngoc Tran
 
DOC
Luận Văn Thạc Sĩ Tích Hợp Csdl Quan Hệ Xml.doc
tcoco3199
 
DOC
Luận Văn Thạc Sĩ Tích Hợp Csdl Quan Hệ Xml.doc
mokoboo56
 
PPTX
Giới thiệu về JAXP
Nguyễn Việt Khoa
 
PDF
Giáo trình c#
khongtoan1991
 
PDF
Pdfc fast food-mastercode.vn
MasterCode.vn
 
PDF
Những điểm mới trong c# 3.0
Trần Thiên Đại
 
Hướng dẫn lập trình quản lý c#
An Nguyen
 
2_Giới thiệu và tạo file dữ liệu dưới dạngXML.pdf
PhamThiThuThuy1
 
Lesson 19.xml
Hallo Patidu
 
Xml
xeroxk
 
Tailieu.vncty.com co ban ve xml
Trần Đức Anh
 
Thiết kế dữ liệu
Nguyen Tran
 
Căn bản về xml
Hieu Meteor
 
Chapter 4 xml schema
Bình Trọng Án
 
Android Nâng cao-Bài 8-JSON & XML Parsing
Phuoc Nguyen
 
hoc ve xml
mrtom16071980
 
Luận Văn Tích Hợp Csdl Quan Hệ Xml.doc
tcoco3199
 
07 x query
Ha Ngoc Tran
 
Luận Văn Thạc Sĩ Tích Hợp Csdl Quan Hệ Xml.doc
tcoco3199
 
Luận Văn Thạc Sĩ Tích Hợp Csdl Quan Hệ Xml.doc
mokoboo56
 
Giới thiệu về JAXP
Nguyễn Việt Khoa
 
Giáo trình c#
khongtoan1991
 
Pdfc fast food-mastercode.vn
MasterCode.vn
 
Những điểm mới trong c# 3.0
Trần Thiên Đại
 
Ad

More from Bình Trọng Án (17)

PDF
A Developer's Guide to CQRS Using .NET Core and MediatR
Bình Trọng Án
 
PDF
Nếu con em vị nói lắp
Bình Trọng Án
 
PDF
Bài giảng chuyên đề - Lê Minh Hoàng
Bình Trọng Án
 
PDF
Tìm hiểu về NodeJs
Bình Trọng Án
 
PDF
Clean code-v2.2
Bình Trọng Án
 
PDF
Các câu chuyện toán học - Tập 3: Khẳng định trong phủ định
Bình Trọng Án
 
DOCX
2816 mcsa--part-11--domain-c111ntroller--join-domain-1
Bình Trọng Án
 
PDF
Chuyên đề group policy
Bình Trọng Án
 
PPT
Attributes & .NET components
Bình Trọng Án
 
DOCX
Ajax Control ToolKit
Bình Trọng Án
 
PPT
Linq intro
Bình Trọng Án
 
DOCX
Sách chữa tật nói lắp Version 1.0 beta
Bình Trọng Án
 
PPT
Mô hình 3 lớp
Bình Trọng Án
 
PPT
Xsd examples
Bình Trọng Án
 
PPT
Displaying XML Documents Using CSS and XSL
Bình Trọng Án
 
PPT
Introduction to XML
Bình Trọng Án
 
A Developer's Guide to CQRS Using .NET Core and MediatR
Bình Trọng Án
 
Nếu con em vị nói lắp
Bình Trọng Án
 
Bài giảng chuyên đề - Lê Minh Hoàng
Bình Trọng Án
 
Tìm hiểu về NodeJs
Bình Trọng Án
 
Clean code-v2.2
Bình Trọng Án
 
Các câu chuyện toán học - Tập 3: Khẳng định trong phủ định
Bình Trọng Án
 
2816 mcsa--part-11--domain-c111ntroller--join-domain-1
Bình Trọng Án
 
Chuyên đề group policy
Bình Trọng Án
 
Attributes & .NET components
Bình Trọng Án
 
Ajax Control ToolKit
Bình Trọng Án
 
Linq intro
Bình Trọng Án
 
Sách chữa tật nói lắp Version 1.0 beta
Bình Trọng Án
 
Mô hình 3 lớp
Bình Trọng Án
 
Xsd examples
Bình Trọng Án
 
Displaying XML Documents Using CSS and XSL
Bình Trọng Án
 
Introduction to XML
Bình Trọng Án
 

LinQ to XML

  • 2. 1. Giới thiệu LINQ to XML: LINQ to XML cung cấp một giao diện lập trình XML. LINQ to XML sử dụng những ngôn ngữ mới nhất của .NET Language Framework và được nâng cấp, thiết kế lại với giao diện lập trình XML Document Object Model (DOM). XML đã được sử dụng rộng rãi để định dạng dữ liệu trong một loạt các ngữ cảnh (các trang web, trong các tập tin cấu hình, trong các tập tin Microsoft Office Word, và trong cơ sở dữ liệu). LINQ to XML có cấu trúc truy vấn tương tự SQL. Nhà phát triển trung bình có thể viết các truy vấn ngắn gọn, mạnh mẽ, viết mã ít hơn nhưng có ý nghĩa nhiều hơn. Họ có thể sử dụng các biểu thức truy vấn từ nhiều dữ liệu các lĩnh vực tại một thời điểm. LINQ to XML cũng giống như Document Object Model (DOM) ở chỗ nó chuyển các tài liệu XML vào bộ nhớ. Bạn có thể truy vấn và sửa đổi các tài liệu, và sau khi bạn chỉnh sửa nó, bạn có thể lưu nó vào một tập tin hoặc xuất nó ra. Tuy nhiên, LINQ to XML khác DOM: Nó cung cấp mô hình đối tượng mới đơn giản hơn và dễ thao tác hơn để làm việc , và đó là tận dụng các cải tiến ngôn ngữ trong Visual C # 2008. Khả năng sử dụng kết quả truy vấn là tham số cho đối tượng XElement và XAttribute cho phép một phương pháp mạnh mẽ để tạo ra cây XML. Phương pháp này, được gọi là functional construction, cho phép các nhà phát triển để dễ dàng chuyển đổi cây XML từ một hình dạng này sang hình dạng khác. Sử dụng LINQ to XML bạn có thể: • Load XML từ nhiều file hoặc luồng. • Xuất XML ra file hoặc luồng. • Truy vấn cây XML bằng những truy vấn LINQ. • Thao tác cây XML trong bộ nhớ. • Biến đổi cây XML từ dạng này sang dạng khác. 2
  • 3. 2. Xây dựng một cây XML bằng Visual C# 2008: 2.1.Tạo một phần tử XML: Cấu trúc XElement(XName name, object content) XElement(XName name) XName: tên phần tử. object: nội dụng của phần tử. Ví dụ sau tạo phần tử <Customer>có nội dung “Adventure Works”. C# XElement n = new XElement("Customer", "Adventure Works"); Console.WriteLine(n); Xml <Customer>Adventure Works</Customer> Tạo phần tử rỗng để trống phân nội dung: C# XElement n = new XElement("Customer"); Console.WriteLine(n); Xml <Customer /> 2.2.Tạo một thuộc tính cho phần tử XML: 3
  • 4. Cấu trúc XAttribute(XName name, object content) Tham số: XName: thuộc tính. object: giá trị của thuộc tính. C# XElement phone = new XElement("Phone", new XAttribute("Type", "Home"), "555-555-5555"); Console.WriteLine(phone); Xml <Phone Type="Home">555-555-5555</Phone> 4
  • 5. 2.3.Tạo ghi chú trong cây XML: Tạo một phần tử gồm một chú thích như một nút con Tên XComment(String) C# XElement root = new XElement("Root", new XComment("This is a comment") ); Console.WriteLine(root); Xml <Root> <!--This is a comment--> </Root> 5
  • 6. 2.4.Xây dựng một cây XML: Sử dụng đối tượng XDocument xây dựng một cây XML. Thông thường ta có thể tạo ra cây XML với nút gốc XElement. Name Description XDocument() Initializes a new instance of the XDocument class. XDocument(Object[]) Initializes a new instance of the XDocument class with the specified content. XDocument(XDocument) Initializes a new instance of the XDocument class from an existing XDocument object. XDocument(XDeclaration, Initializes a new instance of the Object[]) XDocument class with the specified XDeclaration and content. C# XDocument doc = new XDocument( new XComment("This is a comment"), new XElement("Root", new XElement("Info5", "info5"), new XElement("Info6", "info6"), new XElement("Info7", "info7"), new XElement("Info8", "info8") ) ); Console.WriteLine(doc); Xml <!--This is a comment--> <Root> <Child1>data1</Child1> 6
  • 7. <Child2>data2</Child2> <Child3>data3</Child3> <Child2>data4</Child2> </Root> 7
  • 8. 2.5.Đối tượng XDeclaration: Đối tượng XDeclaration được sử dụng để khai báo XML version, encoding, and có thể có hoặc không thuộc tính standalone của một tài liệu XML. Cấu trúc XDeclaration(string version,string encoding,string standalone) C# XDocument doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XComment("This is a comment"), new XElement("Root", "content") ); doc.Save("Root.xml"); Console.WriteLine(File.ReadAllText("Root.xml")); Xml <?xml version="1.0" encoding="utf-8" standalone="yes"?> <!--This is a comment--> <Root>content</Root> 8
  • 9. 2.6.Phương thức XElement.Save: Name Description Save(String) Serialize this element to a file. C# XElement root = new XElement("Root", new XElement("Child", "child content") ); root.Save("Root.xml"); string str = File.ReadAllText("Root.xml"); Console.WriteLine(str); Xml <?xml version="1.0" encoding="utf-8"?> <Root> <Child>child content</Child> </Root> 9
  • 10. 2.7.Phương thức XDocument.Save: Name Description Save(String) Serialize this XDocument to a file. C# XDocument doc = new XDocument( new XElement("Root", new XElement("Child", "content") ) ); doc.Save("Root.xml"); Console.WriteLine(File.ReadAllText("Root.xml")); Xml <?xml version="1.0" encoding="utf-8"?> <Root> <Child>content</Child> </Root> 10
  • 11. 2.8.Phương thức XElement.Load: Name Description Load(String) Loads an XElement from a file. C# XElement xmlTree1 = new XElement("Root", new XElement("Child", "content") ); xmlTree1.Save("Tree.xml"); XElement xmlTree2 = XElement.Load("Tree.xml"); Console.WriteLine(xmlTree2); <Root> <Child>content</Child> </Root> 11
  • 12. 2.9.Phương thức XDocument.Load: Name Description Load(String) Creates a new XDocument from a file. C# XElement xmlTree1 = new XElement("Root", new XElement("Child", "content") ); xmlTree1.Save("Tree.xml"); XDocument xmlTree2 = XDocument.Load("Tree.xml"); Console.WriteLine(xmlTree2); Xml <Root> <Child>content</Child> </Root> 12
  • 13. 3. XML namespace: 3.1.Giới thiệu namespace: XML namespace giúp tránh xung đột giửa các bộ phận khác nhau của một tài liệu XML. khi khai báo một namespace, bạn chọn một tên cục bộ sao cho nó là duy nhất. Những tiền tố làm cho tài liệu XML súc tích và dễ hiểu hơn. Một trong những lợi thế khi sử dụng LINQ to XML với C# là đơn giản hóa những XML name là loại bỏ những thủ tục mà những nhà phát triễn sử dụng tiền tố. khi LINQ load hoặc parse một tài liệu XML, mỗi tiền tố sẽ được xử lý để phù hợp với namespace XML. khi làm việc với tài liệu có namespace, bạn thường truy cập namespace thông qua namespace URI, không thông qua tiền tố namespace. 13
  • 14. 3.2.Tạo một namespace trong cây XML: Xem ví dụ sau: C# Copy Code // Create an XML tree in a namespace, with a specified prefix XNamespace aw = "http://www.adventure-works.com"; XElement root = new XElement(aw + "Root", new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"), new XElement(aw + "Child", "child content") ); Console.WriteLine(root); Xml <aw:Root xmlns:aw="http://www.adventure-works.com"> <aw:Child>child content</aw:Child> </aw:Root> 14
  • 15. 3.3.Điều khiển tiền tố namespace trong cây XML: Ví dụ sau khai báo hai tiền tố namespace. Tên miền http://www.adventure-works.com có tiền tố aw, và www.fourthcoffee.com có tiền tố fc. C# XNamespace aw = "http://www.adventure-works.com"; XNamespace fc = "www.fourthcoffee.com"; XElement root = new XElement(aw + "Root", new XAttribute(XNamespace.Xmlns + "aw", "http://www.adventure-works.com"), new XAttribute(XNamespace.Xmlns + "fc", "www.fourthcoffee.com"), new XElement(fc + "Child", new XElement(aw + "DifferentChild", "other content") ), new XElement(aw + "Child2", "c2 content"), new XElement(fc + "Child3", "c3 content") ); Console.WriteLine(root); Xml <aw:Root xmlns:aw="http://www.adventure-works.com" xmlns:fc="www.fourthcoffee.com"> <fc:Child> <aw:DifferentChild>other content</aw:DifferentChild> </fc:Child> <aw:Child2>c2 content</aw:Child2> <fc:Child3>c3 content</fc:Child3> </aw:Root> 15
  • 16. 3.4.Viết truy vấn LINQ trong namespace: Xem ví dụ sau: C# XNamespace aw = "http://www.adventure-works.com"; XElement root = XElement.Parse( @"<Root xmlns='http://www.adventure-works.com'> <Child>1</Child> <Child>2</Child> <Child>3</Child> <AnotherChild>4</AnotherChild> <AnotherChild>5</AnotherChild> <AnotherChild>6</AnotherChild> </Root>"); IEnumerable<XElement> c1 = from el in root.Elements(aw + "Child") select el; foreach (XElement el in c1) Console.WriteLine((int)el); 1 2 3 16
  • 17. 4. Những thao tác truy vấn cơ bản trên cây XML: 4.1.Tìm một phần tử trong cây XML: Xét ví dụ sau tìm phần tử Address có thuộc tính Type có giá trị là "Billing". C# XElement root = XElement.Load("PurchaseOrder.xml"); IEnumerable<XElement> address = from el in root.Elements("Address") where (string)el.Attribute("Type") == "Billing" select el; foreach (XElement el in address) Console.WriteLine(el); Xml <Address Type="Billing"> <Name>Tai Yee</Name> <Street>8 Oak Avenue</Street> <City>Old Town</City> <State>PA</State> <Zip>95819</Zip> <Country>USA</Country> 17
  • 19. 4.2.Lọc phần tử trong cây XML: Ví dụ sau lọc những phần tử có phần tử con <Type > có Value="Yes". C# XElement root = XElement.Parse(@"<Root> <Child1> <Text>Child One Text</Text> <Type Value=""Yes""/> </Child1> <Child2> <Text>Child Two Text</Text> <Type Value=""Yes""/> </Child2> <Child3> <Text>Child Three Text</Text> <Type Value=""No""/> </Child3> <Child4> <Text>Child Four Text</Text> <Type Value=""Yes""/> </Child4> <Child5> <Text>Child Five Text</Text> </Child5> </Root>"); var cList = from typeElement in root.Elements().Elements("Type") where (string)typeElement.Attribute("Value") == "Yes" select (string)typeElement.Parent.Element("Text"); foreach(string str in cList) Console.WriteLine(str); Child One Text 19
  • 20. Child Two Text Child Four Text 20
  • 21. 4.3.Sắp xếp các phần tử trong cây XML: C# XElement root = XElement.Load("Data.xml"); IEnumerable<decimal> prices = from el in root.Elements("Data") let price = (decimal)el.Element("Price") orderby price select price; foreach (decimal el in prices) Console.WriteLine(el); 0.99 4.95 6.99 24.50 29.00 66.00 89.99 21
  • 22. 4.4.Kết hai cây XML: Ví dụ sau kết những phần tử Customer với những phần tử Order , và tạo ra tài liệu XML mới gồm phần tử CompanyName bên trong order. C# XmlSchemaSet schemas = new XmlSchemaSet(); schemas.Add("", "CustomersOrders.xsd"); Console.Write("Attempting to validate, "); XDocument custOrdDoc = XDocument.Load("CustomersOrders.xml"); bool errors = false; custOrdDoc.Validate(schemas, (o, e) => { Console.WriteLine("{0}", e.Message); errors = true; }); Console.WriteLine("custOrdDoc {0}", errors ? "did not validate" : "validated"); if (!errors) { // Join customers and orders, and create a new XML document with // a different shape. // The new document contains orders only for customers with a // CustomerID > 'K' XElement custOrd = custOrdDoc.Element("Root"); XElement newCustOrd = new XElement("Root", from c in custOrd.Element("Customers").Elements("Customer") join o in custOrd.Element("Orders").Elements("Order") 22
  • 23. on (string)c.Attribute("CustomerID") equals (string)o.Element("CustomerID") where ((string)c.Attribute("CustomerID")).CompareTo("K") > 0 select new XElement("Order", new XElement("CustomerID", (string)c.Attribute("CustomerID")), new XElement("CompanyName", (string)c.Element("CompanyName")), new XElement("ContactName", (string)c.Element("ContactName")), new XElement("EmployeeID", (string)o.Element("EmployeeID")), new XElement("OrderDate", (DateTime)o.Element("OrderDate")) ) ); Console.WriteLine(newCustOrd); } Attempting to validate, custOrdDoc validated <Root> <Order> <CustomerID>LAZYK</CustomerID> <CompanyName>Lazy K Kountry Store</CompanyName> <ContactName>John Steel</ContactName> <EmployeeID>1</EmployeeID> <OrderDate>1997-03-21T00:00:00</OrderDate> </Order> <Order> <CustomerID>LAZYK</CustomerID> <CompanyName>Lazy K Kountry Store</CompanyName> <ContactName>John Steel</ContactName> <EmployeeID>8</EmployeeID> <OrderDate>1997-05-22T00:00:00</OrderDate> </Order> <Order> <CustomerID>LETSS</CustomerID> 23
  • 24. <CompanyName>Let's Stop N Shop</CompanyName> <ContactName>Jaime Yorres</ContactName> <EmployeeID>1</EmployeeID> <OrderDate>1997-06-25T00:00:00</OrderDate> </Order> <Order> <CustomerID>LETSS</CustomerID> <CompanyName>Let's Stop N Shop</CompanyName> <ContactName>Jaime Yorres</ContactName> <EmployeeID>8</EmployeeID> <OrderDate>1997-10-27T00:00:00</OrderDate> </Order> <Order> <CustomerID>LETSS</CustomerID> <CompanyName>Let's Stop N Shop</CompanyName> <ContactName>Jaime Yorres</ContactName> <EmployeeID>6</EmployeeID> <OrderDate>1997-11-10T00:00:00</OrderDate> </Order> <Order> <CustomerID>LETSS</CustomerID> <CompanyName>Let's Stop N Shop</CompanyName> <ContactName>Jaime Yorres</ContactName> <EmployeeID>4</EmployeeID> <OrderDate>1998-02-12T00:00:00</OrderDate> </Order> </Root> 24
  • 25. 4.5.Nhóm các phần tử trong một cây XML: Ví dụ nhóm dữ liệu theo loại, sau đó tạo ra một tập tin XML mới, trong đó phân cấp XML theo nhóm. C# XElement doc = XElement.Load("Data.xml"); var newData = new XElement("Root", from data in doc.Elements("Data") group data by (string)data.Element("Category") into groupedData select new XElement("Group", new XAttribute("ID", groupedData.Key), from g in groupedData select new XElement("Data", g.Element("Quantity"), g.Element("Price") ) ) ); Console.WriteLine(newData); Xml <Root> <Group ID="A"> 25
  • 26. <Data> <Quantity>3</Quantity> <Price>24.50</Price> </Data> <Data> <Quantity>5</Quantity> <Price>4.95</Price> </Data> <Data> <Quantity>3</Quantity> <Price>66.00</Price> </Data> <Data> <Quantity>15</Quantity> <Price>29.00</Price> </Data> </Group> <Group ID="B"> <Data> <Quantity>1</Quantity> <Price>89.99</Price> </Data> 26
  • 27. <Data> <Quantity>10</Quantity> <Price>.99</Price> </Data> <Data> <Quantity>8</Quantity> <Price>6.99</Price> </Data> </Group> </Root> 27
  • 28. 5. Những thao tác biến đổi trên cây XML: 5.1.Thêm phần tử, thuộc tính và nút vào một cây XML: Thêm nút vào cuối cây hoặc đầu cây dùng phương thức .Add và .AddFirst . C# XElement xmlTree = new XElement("Root", new XElement("Child1", 1), new XElement("Child2", 2), new XElement("Child3", 3), new XElement("Child4", 4), new XElement("Child5", 5) ); xmlTree.Add(new XElement("NewChild", "new content")); Console.WriteLine(xmlTree); <Root> <Child1>1</Child1> <Child2>2</Child2> <Child3>3</Child3> <Child4>4</Child4> <Child5>5</Child5> <NewChild>new content</NewChild> 28
  • 29. </Root> 29
  • 30. 5.2.Thay đổi phần tử, thuộc tính và nút của một cây XML: Sử dụng phương thức XAttribute.SetValue thay đổi giá trị thuộc tính "Att" từ"root" thành"new content". C# XElement root = new XElement("Root", new XAttribute("Att", "root"), (“Root”) ); Console.WriteLine(root); Console.WriteLine(“---------------”) XAttribute att = root.Attribute("Att"); att.SetValue("new content"); root.SetValue("new content"); Console.WriteLine(root); <Root Att="root">Root</Root> <--------------> <Root Att="new content">new content</Root> Sử dụng phương thức XNode.ReplaceWith thay đổi nút có tên "Child3"có nội dung "child3 content" thành "NewChild" nội dung "new content" . C# XElement xmlTree = new XElement("Root", new XElement("Child1", "child1 content"), new XElement("Child2", "child2 content"), new XElement("Child3", "child3 content"), new XElement("Child4", "child4 content"), new XElement("Child5", "child5 content") ); XElement child3 = xmlTree.Element("Child3"); child3.ReplaceWith( new XElement("NewChild", "new content") ); 30
  • 31. Console.WriteLine(xmlTree); Xml <Root> <Child1>child1 content</Child1> <Child2>child2 content</Child2> <NewChild>new content</NewChild> <Child4>child4 content</Child4> <Child5>child5 content</Child5> </Root> Thiết lập giá trị của lớp con bằng hàm XElement.SetElementValue. C# // Create an element with no content XElement root = new XElement("Root"); // Add some name/value pairs. root.SetElementValue("Ele1", 1); root.SetElementValue("Ele2", 2); root.SetElementValue("Ele3", 3); Console.WriteLine(root); // Modify one of the name/value pairs. root.SetElementValue("Ele2", 22); Console.WriteLine(root); // Remove one of the name/value pairs. root.SetElementValue("Ele3", null); Console.WriteLine(root); <Root> <Ele1>1</Ele1> <Ele2>2</Ele2> <Ele3>3</Ele3> </Root> <Root> 31
  • 32. <Ele1>1</Ele1> <Ele2>22</Ele2> <Ele3>3</Ele3> </Root> <Root> <Ele1>1</Ele1> <Ele2>22</Ele2> </Root> 32
  • 33. 5.3.Xóa phần tử, thuộc tính và nút từ một cây XML: Ví dụ sau dùng phương thức XElement.RemoveAll xóa những phần tử con và thuộc tính của một cây XML C# XElement root = new XElement("Root", new XAttribute("Att1", 1), new XAttribute("Att2", 2), new XAttribute("Att3", 3), new XElement("Child1", 1), new XElement("Child2", 2), new XElement("Child3", 3) ); root.RemoveAll(); // removes children elements and attributes of root Console.WriteLine(root); Xml <Root /> Ví dụ tiếp theo dùng phương thức XElement.RemoveAttributes xóa toàn bộ thuộc tính của một cây XML. C# XElement root = new XElement("Root", new XAttribute("Att1", 1), new XAttribute("Att2", 2), new XAttribute("Att3", 3), new XElement("Child1", 1), new XElement("Child2", 2), new XElement("Child3", 3) ); root.RemoveAttributes(); Console.WriteLine(root); Xml 33
  • 34. <Root> <Child1>1</Child1> <Child2>2</Child2> <Child3>3</Child3> </Root> Dùng phương thức XNode.Remove xóa một nút của cây XML C# XElement xmlTree = new XElement("Root", new XElement("Child1", "child1 content"), new XElement("Child2", "child2 content"), new XElement("Child3", "child3 content"), new XElement("Child4", "child4 content"), new XElement("Child5", "child5 content") ); XElement child3 = xmlTree.Element("Child3"); child3.Remove(); Console.WriteLine(xmlTree); Xml <Root> <Child1>child1 content</Child1> <Child2>child2 content</Child2> <Child4>child4 content</Child4> <Child5>child5 content</Child5> </Root> 34