SlideShare uma empresa Scribd logo
1 de 34
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

Mais conteúdo relacionado

Mais procurados

tổng hợp bài tập java có đáp án chi tiết
 tổng hợp bài tập java có đáp án chi tiết tổng hợp bài tập java có đáp án chi tiết
tổng hợp bài tập java có đáp án chi tiết
Hoàng Trí Phan
 
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng HồBáo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
zDollz Lovez
 
Bài tập nhập môn lập trình
Bài tập nhập môn lập trìnhBài tập nhập môn lập trình
Bài tập nhập môn lập trình
Huy Rùa
 
Công nghệ phần mềm chuong 1
Công nghệ phần mềm chuong 1Công nghệ phần mềm chuong 1
Công nghệ phần mềm chuong 1
laducqb
 

Mais procurados (20)

Giải số bằng mathlab
Giải số bằng mathlabGiải số bằng mathlab
Giải số bằng mathlab
 
Đề thi môn công nghệ phần mềm
Đề thi môn công nghệ phần mềmĐề thi môn công nghệ phần mềm
Đề thi môn công nghệ phần mềm
 
Postgresql security
Postgresql securityPostgresql security
Postgresql security
 
tổng hợp bài tập java có đáp án chi tiết
 tổng hợp bài tập java có đáp án chi tiết tổng hợp bài tập java có đáp án chi tiết
tổng hợp bài tập java có đáp án chi tiết
 
Đề thi Kỹ thuật lập trình có lời giải
Đề thi Kỹ thuật lập trình có lời giảiĐề thi Kỹ thuật lập trình có lời giải
Đề thi Kỹ thuật lập trình có lời giải
 
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng HồBáo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
Báo Cáo Đồ Án 2 : Thiết Kế Web Bán Đồng Hồ
 
Dữ liệu không gian trên SQL Server - (Spatial Data in SQL Server)
Dữ liệu không gian trên SQL Server - (Spatial Data in SQL Server)Dữ liệu không gian trên SQL Server - (Spatial Data in SQL Server)
Dữ liệu không gian trên SQL Server - (Spatial Data in SQL Server)
 
Slide đồ án tốt nghiệp
Slide đồ án tốt nghiệpSlide đồ án tốt nghiệp
Slide đồ án tốt nghiệp
 
Cs lab04 win-form assignment
Cs lab04   win-form assignmentCs lab04   win-form assignment
Cs lab04 win-form assignment
 
[Đồ án môn học] - Đề tài: Tìm hiểu Git và Github
[Đồ án môn học] - Đề tài: Tìm hiểu Git và Github[Đồ án môn học] - Đề tài: Tìm hiểu Git và Github
[Đồ án môn học] - Đề tài: Tìm hiểu Git và Github
 
Quy trình gán tải và tổ hợp tải trọng trong Robot Structural
Quy trình gán tải và tổ hợp tải trọng trong Robot StructuralQuy trình gán tải và tổ hợp tải trọng trong Robot Structural
Quy trình gán tải và tổ hợp tải trọng trong Robot Structural
 
Bai1
Bai1Bai1
Bai1
 
Bìa báo cáo
Bìa báo cáoBìa báo cáo
Bìa báo cáo
 
Nhập môn công nghệ phần mềm
Nhập môn công nghệ phần mềmNhập môn công nghệ phần mềm
Nhập môn công nghệ phần mềm
 
Bài giảng công nghệ phần mềm PTIT
Bài giảng công nghệ phần mềm PTITBài giảng công nghệ phần mềm PTIT
Bài giảng công nghệ phần mềm PTIT
 
Bài tập nhập môn lập trình
Bài tập nhập môn lập trìnhBài tập nhập môn lập trình
Bài tập nhập môn lập trình
 
Kĩ thuật lọc ảnh và ứng dụng trong lọc nhiễu làm trơn
Kĩ thuật lọc ảnh và ứng dụng trong lọc nhiễu làm trơnKĩ thuật lọc ảnh và ứng dụng trong lọc nhiễu làm trơn
Kĩ thuật lọc ảnh và ứng dụng trong lọc nhiễu làm trơn
 
Tin học cơ sở - FPT Polytechnic
Tin học cơ sở - FPT PolytechnicTin học cơ sở - FPT Polytechnic
Tin học cơ sở - FPT Polytechnic
 
Báo cáo đồ án tôt nghiệp: Xây dựng Website bán hàng thông minh
Báo cáo đồ án tôt nghiệp: Xây dựng Website bán hàng thông minhBáo cáo đồ án tôt nghiệp: Xây dựng Website bán hàng thông minh
Báo cáo đồ án tôt nghiệp: Xây dựng Website bán hàng thông minh
 
Công nghệ phần mềm chuong 1
Công nghệ phần mềm chuong 1Công nghệ phần mềm chuong 1
Công nghệ phần mềm chuong 1
 

Destaque (6)

Efs
EfsEfs
Efs
 
Cơ bản về XML cho người mới sử dụng
Cơ bản về XML cho người mới sử dụngCơ bản về XML cho người mới sử dụng
Cơ bản về XML cho người mới sử dụng
 
Tai lieu-xml
Tai lieu-xmlTai lieu-xml
Tai lieu-xml
 
template magento
template magentotemplate magento
template magento
 
Tỷ lệ vàng - một phát hiện vĩ đại của hình học
Tỷ lệ vàng - một phát hiện vĩ đại của hình họcTỷ lệ vàng - một phát hiện vĩ đại của hình học
Tỷ lệ vàng - một phát hiện vĩ đại của hình học
 
Luyện dịch Việt Anh
Luyện dịch Việt AnhLuyện dịch Việt Anh
Luyện dịch Việt Anh
 

Semelhante a LinQ to XML

Them,xoa,sua data trong xml
Them,xoa,sua data trong xmlThem,xoa,sua data trong xml
Them,xoa,sua data trong xml
Nguyễn Linh
 
Giao trinh java script
Giao trinh java scriptGiao trinh java script
Giao trinh java script
hieusy
 
Lap trinhcosodulieuvoi c-sharp_phan-1
Lap trinhcosodulieuvoi c-sharp_phan-1Lap trinhcosodulieuvoi c-sharp_phan-1
Lap trinhcosodulieuvoi c-sharp_phan-1
Hiển Phùng
 
Giao trinh asp.ne_tvoi_csharp
Giao trinh asp.ne_tvoi_csharpGiao trinh asp.ne_tvoi_csharp
Giao trinh asp.ne_tvoi_csharp
ngohanty13
 
Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952
Ham Chơi
 
Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingAndroid Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML Parsing
Phuoc Nguyen
 
6 - Lập trình C++ cơ bản_print.pdf
6 - Lập trình C++ cơ bản_print.pdf6 - Lập trình C++ cơ bản_print.pdf
6 - Lập trình C++ cơ bản_print.pdf
SonNguyen642431
 
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
Dao Uit
 
Chươngii
ChươngiiChươngii
Chươngii
jvinhit
 
Hỏi tình hình bk tiny bktiny-hdsd
Hỏi tình hình bk tiny   bktiny-hdsdHỏi tình hình bk tiny   bktiny-hdsd
Hỏi tình hình bk tiny bktiny-hdsd
Vu Hung Nguyen
 

Semelhante a LinQ to XML (20)

LinQ
LinQLinQ
LinQ
 
Sơ lược về StAX
Sơ lược về StAXSơ lược về StAX
Sơ lược về StAX
 
Giới thiệu ngắn về DOM
Giới thiệu ngắn về DOMGiới thiệu ngắn về DOM
Giới thiệu ngắn về DOM
 
Asp control
Asp controlAsp control
Asp control
 
Them,xoa,sua data trong xml
Them,xoa,sua data trong xmlThem,xoa,sua data trong xml
Them,xoa,sua data trong xml
 
Giao trinh java script
Giao trinh java scriptGiao trinh java script
Giao trinh java script
 
Lap trinhcosodulieuvoi c-sharp_phan-1
Lap trinhcosodulieuvoi c-sharp_phan-1Lap trinhcosodulieuvoi c-sharp_phan-1
Lap trinhcosodulieuvoi c-sharp_phan-1
 
Giao trinh asp.ne_tvoi_csharp
Giao trinh asp.ne_tvoi_csharpGiao trinh asp.ne_tvoi_csharp
Giao trinh asp.ne_tvoi_csharp
 
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầu
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầuTài liệu tìm hiểu jQuery dành cho người mới bắt đầu
Tài liệu tìm hiểu jQuery dành cho người mới bắt đầu
 
Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952Bai1 gioi thieu_servlet_va_jsp_8952
Bai1 gioi thieu_servlet_va_jsp_8952
 
Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingAndroid Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML Parsing
 
6 - Lập trình C++ cơ bản_print.pdf
6 - Lập trình C++ cơ bản_print.pdf6 - Lập trình C++ cơ bản_print.pdf
6 - Lập trình C++ cơ bản_print.pdf
 
Semina Kết nối nguồn dữ liệu từ Internet
Semina Kết nối nguồn dữ liệu từ Internet Semina Kết nối nguồn dữ liệu từ Internet
Semina Kết nối nguồn dữ liệu từ Internet
 
Bài 5: Làm quen với lập trình CSDL ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
Bài 5: Làm quen với lập trình CSDL ASP.NET - Giáo trình FPT - Có ví dụ kèm theoBài 5: Làm quen với lập trình CSDL ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
Bài 5: Làm quen với lập trình CSDL ASP.NET - Giáo trình FPT - Có ví dụ kèm theo
 
Cach su dung data reader
Cach su dung data readerCach su dung data reader
Cach su dung data reader
 
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#2.gioi thieu co ban ado.net cho nguoi lap trinh c#
2.gioi thieu co ban ado.net cho nguoi lap trinh c#
 
Chươngii
ChươngiiChươngii
Chươngii
 
Thuc hanh ado.net_bai_03
Thuc hanh ado.net_bai_03Thuc hanh ado.net_bai_03
Thuc hanh ado.net_bai_03
 
Hỏi tình hình bk tiny bktiny-hdsd
Hỏi tình hình bk tiny   bktiny-hdsdHỏi tình hình bk tiny   bktiny-hdsd
Hỏi tình hình bk tiny bktiny-hdsd
 
tài liệu Mã nguồn mở Lap trình shells
tài liệu Mã nguồn mở  Lap trình shellstài liệu Mã nguồn mở  Lap trình shells
tài liệu Mã nguồn mở Lap trình shells
 

Mais de Bình Trọng Án

2816 mcsa--part-11--domain-c111ntroller--join-domain-1
2816 mcsa--part-11--domain-c111ntroller--join-domain-12816 mcsa--part-11--domain-c111ntroller--join-domain-1
2816 mcsa--part-11--domain-c111ntroller--join-domain-1
Bình Trọng Án
 
Displaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSLDisplaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSL
Bình Trọng Án
 

Mais de Bình Trọng Án (18)

A Developer's Guide to CQRS Using .NET Core and MediatR
A Developer's Guide to CQRS Using .NET Core and MediatRA Developer's Guide to CQRS Using .NET Core and MediatR
A Developer's Guide to CQRS Using .NET Core and MediatR
 
Nếu con em vị nói lắp
Nếu con em vị nói lắpNếu con em vị nói lắp
Nếu con em vị nói lắp
 
Bài giảng chuyên đề - Lê Minh Hoàng
Bài giảng chuyên đề - Lê Minh HoàngBài giảng chuyên đề - Lê Minh Hoàng
Bài giảng chuyên đề - Lê Minh Hoàng
 
Tìm hiểu về NodeJs
Tìm hiểu về NodeJsTìm hiểu về NodeJs
Tìm hiểu về NodeJs
 
Clean code-v2.2
Clean code-v2.2Clean code-v2.2
Clean code-v2.2
 
Các câu chuyện toán học - Tập 3: Khẳng định trong phủ định
Các câu chuyện toán học - Tập 3: Khẳng định trong phủ địnhCác câu chuyện toán học - Tập 3: Khẳng định trong phủ định
Các câu chuyện toán học - Tập 3: Khẳng định trong phủ định
 
2816 mcsa--part-11--domain-c111ntroller--join-domain-1
2816 mcsa--part-11--domain-c111ntroller--join-domain-12816 mcsa--part-11--domain-c111ntroller--join-domain-1
2816 mcsa--part-11--domain-c111ntroller--join-domain-1
 
Chuyên đề group policy
Chuyên đề group policyChuyên đề group policy
Chuyên đề group policy
 
Chapter 4 xml schema
Chapter 4   xml schemaChapter 4   xml schema
Chapter 4 xml schema
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
 
Ajax Control ToolKit
Ajax Control ToolKitAjax Control ToolKit
Ajax Control ToolKit
 
Linq intro
Linq introLinq intro
Linq intro
 
Sách chữa tật nói lắp Version 1.0 beta
Sách chữa tật nói lắp Version 1.0 betaSách chữa tật nói lắp Version 1.0 beta
Sách chữa tật nói lắp Version 1.0 beta
 
Mô hình 3 lớp
Mô hình 3 lớpMô hình 3 lớp
Mô hình 3 lớp
 
Xsd examples
Xsd examplesXsd examples
Xsd examples
 
Displaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSLDisplaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSL
 
Tp2
Tp2Tp2
Tp2
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 

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