SlideShare une entreprise Scribd logo
1  sur  38
LINQ TO XML .NET 4.0
      WINP1.C24
Nội dung


    Tổng quan về XML và LINQ



        Truy vấn XML bằng LINQ



        Tạo và Biến đổi một tài liệu XML



    Danh sách nhóm và tài liệu tham khảo




2                                          SE-PRO
Tổng quan về XML và LINQ




3                              SE-PRO
Tổng quan về XML và LINQ

                                Lịch sử hình thành                                 2005


              1986
                                                                                 XML v6.0
 SGML
 ( Standard                                               1996
Generalized
Markup Language)
ra đời.
 Rắc rối, không                                           XML (eXtensible
thích hợp cho việc           1991                         Markup
truyền tải thông tin                                      Language)version 1.0
                                                          ra đời giải quyết
                                                          được các nhược
                        HTML (Hyper Text Markup          điểm trên
                       Language) ra đời.
                       Chú trọng đến việc hiển thị
                       thông tin hơn là truyền tải, còn
                       nhiều nhược điểm

  4                                                                                       SE-PRO
Tổng quan về XML và LINQ



                               •
 Thiết kế nhằm trình bày dữ
                                          c nhau
liệu.

                              • Mô tả
                                                     u
          o

         thông tin            •         thông tin


    5                                                    SE-PRO
Tổng quan về XML và LINQ
             XML đang thay đổi web như thế
                         nào?




Đơn giản hóa việc   Cho phép mã hóa   Cho phép tìm kiếm
 trao đổi dữ liệu     thông minh         thông minh




   6                                               SE-PRO
Các thành phần của một file xml
                                             Bảng mã lưu
 Phần              GameData.xml
khai báo           <? xml version="1.0" encoding="utf-8“ standalone = "yes“ ?>
                   <!--Thông tin Level -->                                       Chú thích
 Thẻ
                   <Levels>
bắt đầu             <Level levelIndex="1">
                      <ImagePath>Girl.jpg</ImagePath>
                                                            Một
                      <Rows>3</Rows>
         Phần         <Cols>3</Cols>
                                                            Element
         thân       </Level>
          của      <Level levelIndex=“2“ >
           tài        <ImagePath>Lady.jpg</ImagePath>                            Attribute
          liệu        <Rows>4</Rows>
                      <Cols>4</Cols>                                             Một Tag
                    </Level>
                   </Levels>



         Thẻ kết thúc
     7                                                                           SE-PRO
Giới thiệu về LINQ
LINQ (Language Integrated Query) – Ngôn ngữ
 truy vấn tích hợp - Ngôn ngữ thống nhất cách
 thức truy xuất dữ liệu trong .NET.

Được phát triển từ năm 2003, và được công bố
 tại Hội nghị Microsoft Professional Developers
 vào 2005 do Anders Hejlsberg và nhóm của ông
 đã trình bày.

Được tích hợp sẵn trong Visual Studio 2008
 (.NET 3.5).

 8                                            SE-PRO
Giới thiệu về LINQ
• LINQ được phân thành 3 loại:
   LINQ to Objects
   LINQ to XML
   LINQ to SQL

• Lợi ích sử dụng LINQ
 Nó cung cấp một cách chung để truy xuất dữ
  liệu từ bất kỳ nguồn nào với cùng một cú pháp.
 Giúp thực hiện truy vấn một cách dễ dàng hơn.
 Được tích hợp như cú pháp của ngôn ngữ lập
  trình.

 9                                            SE-PRO
Nội dung


     Tổng quan về XML và LINQ



          Truy vấn XML bằng LINQ



         Tạo và Biến đổi một tài liệu XML



     Danh sách nhóm và tài liệu tham khảo




10                                          SE-PRO
LINQ TO XML(1)

 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). Tuy
nhiên 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.

 LINQ to XML có cấu trúc truy vấn tương tự SQL.

 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

11                                                       SE-PRO
LINQ TO XML(2)

 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.

12                                       SE-PRO
Truy vấn XML bằng LINQ(1)
 IEnumerable<XElement> Descendants( string ElementName)
   Trả ra một Collections XElement giúp bạn truy xuất đến
     Element có tên ElementName.
 IEnumerable<XElement> Ancestor();
   Trả ra một Collections các XElement chứa nó (parent).
 IEnumerable<XElement> ElementBeforeSelf();
   Trả ra một Collections các XElement đứng trước Element hiện
    tại.
 IEnumerable<XElement> ElementAfterSelf();
   Trả ra một Collections các XElement đứng sau Element hiện
    tại.


  13                                                    SE-PRO
Truy vấn XML bằng LINQ(2)
XElement Parent();
      Trả ra một XElement giúp bạn truy xuất đến Element
       cha(chứa nó).
bool HasElement();
      Kiểm tra xem Element hiện tại có Element con nào
       không.
bool HasAttribute();
      Kiểm tra xem Element hiện tại có Attribute nào không.
void Save( string URL);
      Lưu một tài liệu XML xuống file URL
bool IsEmpty();
      Kiểm tra xem Element hiện tại có rỗng không.
14                                                          SE-PRO
Truy vấn XML bằng LINQ(4)
Ba phần cơ bản của một truy vấn XML
1. Có được các dữ liệu nguồn.                  Lấy nội dung tag Rows của
2. Tạo các truy vấn.                           Element có levelIndex == 2
3. Thực hiện các truy vấn.
using System.Xml.Linq;                         GameData.xml
...                                            <? xml version="1.0" encoding="utf-8"?>
XDocument XDoc = new                           <!--Thông tin Level -->
XDocument.Load(“GameData.xml”);                <Levels>
                                                <Level levelIndex="1">
var query = from q in                             <ImagePath>Girl.jpg</ImagePath>
XDoc.Descendants(“Levels”).Elements(“Level”)      <Rows>3</Rows>
where (int)q.XAttribute(“levelIndex”) == 2        <Cols>3</Cols>
select q;                                       </Level>
                                               <Level levelIndex=“2">
foreach( var p in query)                          <ImagePath>Boy.jpg</ImagePath>
{                                                 <Rows>4</Rows>
   System.Console.WriteLine(“Rows: {0}”,          <Cols>4</Cols>
          p.Element(“Rows”).Value);             </Level>
}                                              </Levels>

      15                                                                       SE-PRO
Nội dung


     Tổng quan về XML và LINQ



         Truy vấn XML bằng LINQ



         Tạo và Biến đổi một tài liệu XML



     Danh sách nhóm và tài liệu tham khảo




16                                          SE-PRO
Tạo và Biến đổi một tài liệu XML
Tạo một tài liệu XML:
Ta sử dụng hàm khởi tạo XDocument();
       XDocument(XDeclaration xd, param object[] content);
       Trong đó:
        XDeclaration(string version, string encoding, string standalone)
          version là phiên bản của tài liệu “1.0”.
          encoding là bảng mã lữu trữ “UTF-8”.
          standalone tồn tại một mình hay không “Yes” hoặc “No”.
          Thường thì không có thuộc tính này cũng không xao cả.
        object[] là danh sách các đối tượng cần đưa vào tài liệu:
           XComment(string comment )
               Chứa chú thích cho tài liệu comment = “Chú thích đây” sẽ
          cho kết quả <!-- Chú thích đây --!>
           XElement( XName name, param object[] content)
               • XName là tên của Element <name> </name>
               •object[] tương tự object[] nói ở trên.
 Dùng hàm Save( string URL ) để lưu xuống file URL
17                                                                 SE-PRO
Tạo và Biến đổi một tài liệu XML

Tạo một tài liệu XML:
Code:                                           GameData.xml
using System.Xml.Linq;                          <? xml version="1.0" encoding="utf-8"?>
...                                             <!--Thông tin Level -->
                                                <Levels>
XDocument XDoc = new XDocument(
                                                 <Level levelIndex="1">
(
                                                   <ImagePath>Girl.jpg</ImagePath>
   new XDeclaration("1.0", "utf-8”),
                                                   <Rows>3</Rows>
   new XComment("Thông tin Level "),
                                                   <Cols>3</Cols>
   new XElement(“Level",
                                                 </Level>
       new XAttribute(“levelIndex“,1),
                                                </Levels>
       new XElement("ImagePath", “Girl.jpg”),
       new XElement("Rows", 3),
       new XElement(“Cols", 3),
);

XDoc. Save(“GameData.xml”);



      18                                                                        SE-PRO
Tạo và Biến đổi một tài liệu XML
Hoặc táo bạo hơn một chút với phương thức Parse()
Code:                                         GameData.xml
using System.Xml.Linq;                        <? xml version="1.0" encoding="utf-8"?>
...                                           <!--Thông tin Level -->
                                              <Levels>
XDocument XDoc = new XDocument(
                                               <Level levelIndex="1">
   new XDeclaration("1.0", "utf-8", "yes"),
                                                 <ImagePath>Girl.jpg</ImagePath>
   new XComment("Thông tin Level "),
                                                 <Rows>3</Rows>
   new XElement.Parse(
                                                 <Cols>3</Cols>
     “<Levels>
                                               </Level>
       <Level levelIndex="1">
                                              </Levels>
        <ImagePath>Girl.jpg</ImagePath>
        <Rows>3</Rows>
        <Cols>3</Cols>
        </Level>
      </Levels>”
   )
);
XDoc. Save(“GameData.xml”);

      19                                                                      SE-PRO
Thêm một Element(1)

           • void Add( XElement content);
     Add   • Thêm content như là một Node con vào đầu Element hiện tại.



           • void AddFist( XElement content);
AddFist    • Thêm content như là một Node con vào cuối Element hiện tại.



                  • void AddAfterSelf( XElement content);
 AddAfterSelf     • Chèn một element vào sau element hiện tại



                  • void AddBeforeSelf( XElement content);
AddBeforeSelf     • Chèn một element vào trước element hiện tại


20                                                                   SE-PRO
Thêm một Element(2)
                    • void Add( XElement content);
       Add          • Thêm content như là một Node con vào cuối Element hiện tại.

 Code:      Add một XElement vào trong <Levels>_</Levels>   GameData.xml
 using System.Xml.Linq;                                     <? xml version="1.0" encoding="utf-8"?>
 ...                                                        <!--Thông tin mỗi Level trong game-->
                                                            <Levels>
 XDocument XDoc =
                                                             <Level levelIndex="1">
                                                              <Level levelIndex="1">
    new XDocument.Load(“GameData.xml”);
                                                               <ImagePath>Girl.jpg</ImagePath>
                                                                <ImagePath>Girl.jpg</ImagePath>
                                                               <Rows>3</Rows>
                                                                <Rows>3</Rows>
 XDoc.Element ("Levels“).Add(
                                                               <Cols>3</Cols>
                                                                <Cols>3</Cols>
    new XElement(
                                                             </Level>
                                                              </Level>
       "Level“,
                                                            </Levels>
                                                              <Level levelIndex=“2">
       new XAttribute(“levelIndex", 2),
       new XElement("ImagePath", “Laydy.jpg”),                  <ImagePath>Lady.jpg</ImagePath>
       new XElement("Rows“, 3),                                 <Rows>3</Rows>
       new XElement("Cols", 4)                                  <Cols>4</Cols>
     )                                                        </Level>
 );                                                         </Levels>
 XDoc. Save(“GameData.xml”);

XDoc.Add(.......);        Error !  Vị trí cần chèn vào không phải là một XElement
       21                                                                                   SE-PRO
Thêm một Element(3)
                    • void AddFist( XElement content);
  AddFist
                    • Thêm content như là một Node con vào đầu Element hiện tại.

 Code:      Add một XElement vào trong <Levels>_</Levels>   GameData.xml
 using System.Xml.Linq;                                     <? xml version="1.0" encoding="utf-8"?>
                                                            <!--Thông tin mỗi Level trong game-->
 ...                                                        <Levels>
 XDocument XDoc =                                            <Level levelIndex="1">
                                                            <Level levelIndex=“2">
    new XDocument.Load(“GameData.xml”);                        <ImagePath>Girl.jpg</ImagePath>
                                                                <ImagePath>Lady.jpg</ImagePath>
                                                               <Rows>3</Rows>
                                                                <Rows>3</Rows>
 XDoc.Element ("Levels“).AddFirst(                             <Cols>3</Cols>
                                                                <Cols>4</Cols>
    new XElement(                                            </Level>
                                                              </Level>
       "Level“,                                             </Levels>
                                                              <Level levelIndex="1">
       new XAttribute(“levelIndex", 2),
                                                                <ImagePath>Girl.jpg</ImagePath>
       new XElement("ImagePath", “Laydy.jpg”),
                                                                <Rows>3</Rows>
       new XElement("Rows“, 3),
                                                                <Cols>3</Cols>
       new XElement("Cols", 4)
                                                              </Level>
     )
                                                            </Levels>
 );
 XDoc. Save(“GameData.xml”);

 XDoc.Add(.......);        Error !  Vị trí cần chèn vào không phải là một XElement.
       22                                                                                   SE-PRO
Thêm một Element(4)
                             • void AddAfterSelf( XElement content);
  AddAfterSelf               • Chèn một element vào sau element hiện tại

Code:      Add một XElement sau <Level levelIndex="1“>   GameData.xml
using System.Xml.Linq;                                   <? xml version="1.0" encoding="utf-8"?>
...                                                      <!--Thông tin mỗi Level trong game-->
XDocument XDoc =                                         <Levels>
                                                          <Level levelIndex="1">
                                                           <Level levelIndex="1">
   new XDocument.Load(“GameData.xml”);
                                                            <ImagePath>Girl.jpg</ImagePath>
                                                             <ImagePath>Girl.jpg</ImagePath>
                                                            <Rows>3</Rows>
                                                             <Rows>3</Rows>
XDoc.Descendants(“Levels”).Elements
                                                            <Cols>3</Cols>
                                                             <Cols>3</Cols>
("Level“).Last().AddAfterSelf(
                                                          </Level>
                                                           </Level>
   new XElement(
                                                         </Levels>
                                                           <Level levelIndex=“2">
      "Level“,
      new XAttribute(“levelIndex", 2),                       <ImagePath>Lady.jpg</ImagePath>
      new XElement("ImagePath", “Laydy.jpg”),                <Rows>3</Rows>
      new XElement("Rows“, 3),                               <Cols>4</Cols>
      new XElement("Cols", 4)                              </Level>
    )                                                    </Levels>
);
XDoc. Save(“GameData.xml”);
      23                                                                                 SE-PRO
Thêm một Element(5)
                             • void AddBeforeSelf( XElement content);
AddBeforeSelf                • Chèn một element vào trước element hiện tại

Code:      Add một XElement trước <Level levelIndex="1“>   GameData.xml
using System.Xml.Linq;                                     <? xml version="1.0" encoding="utf-8"?>
...                                                        <!--Thông tin mỗi Level trong game-->
XDocument XDoc =                                           <Levels>
                                                            <Level levelIndex="1">
                                                           <Level levelIndex=“2">
   new XDocument.Load(“GameData.xml”);
                                                              <ImagePath>Girl.jpg</ImagePath>
                                                               <ImagePath>Lady.jpg</ImagePath>
                                                              <Rows>3</Rows>
                                                               <Rows>3</Rows>
XDoc.Descendants(“Levels”).Elements
                                                              <Cols>3</Cols>
                                                               <Cols>4</Cols>
("Level“).Last().AddBeforeSelf(
                                                            </Level>
                                                             </Level>
   new XElement(
                                                           </Levels>
                                                             <Level levelIndex="1">
      "Level“,
      new XAttribute(“levelIndex", 2),                         <ImagePath>Girl.jpg</ImagePath>
      new XElement("ImagePath", “Laydy.jpg”),                  <Rows>3</Rows>
      new XElement("Rows“, 3),                                 <Cols>3</Cols>
      new XElement("Cols", 4)                                </Level>
    )                                                      </Levels>
);
XDoc. Save(“GameData.xml”);
      24                                                                                   SE-PRO
Thêm một Element(6)

Kết luận:

 Trong hai 4 ví dụ trên thì hai hàm Add() và AddAfterSelf() cho cùng một kết
quả chỉ khác nhau ở vị trí Add vào:

o XDoc.Element ("Levels“).Add()

o XDoc.Descendants(“Levels”).Elements ("Level“).Last().AddAfterSelf()


 Tương tự với hai hàm AddFirst() và AddBeforeSelf().




  25                                                                    SE-PRO
Cập nhật một Element(1)

            • VD: XElement XE; XE.Value = “123”;
 Value      • Một dạng Properties giúp đặt giá trị cho một element một cách trực
              tiếp.


              • SetValue(object value);
 SetValue     • Đặt giá trị cho element hiện tại giá trị là value vì là kiểu object
                nên nó cũng có thể là cả một XElement.


                    • SetAttributeValue(XName name, object value);
SetAttributeValue
                    • Đặt giá trị value cho “attribute” của element tên name.


                      • SetElementValue(XName name, object value);
 SetElementValue      • Đặt giá trị cho “element” tên name giá trị là value vì là
                        kiểu object nên nó cũng có thể là một XElement.

26                                                                            SE-PRO
Cập nhật một Element(2)

                 • VD: XElement XE; XE.Value = “123”;
 Value           • Một dạng Properties giúp đặt giá trị cho một element một cách trực tiếp.


Muốn cập nhật phải tìm được XElement trong tài liệu trước.

Code:      Thay đổi ImagePath của <Level levelIndex="1“>   GameData.xml
using System.Xml.Linq;                                     <? xml version="1.0" encoding="utf-8"?>
                                                           <? xml version="1.0" encoding="utf-8"?>
...                                                        <!--Thông tin mỗi Level trong game-->
                                                           <!--Thông tin mỗi Level trong game-->
XDocument XDoc =                                           <Levels>
                                                           <Levels>
         new XDocument.Load(“GameData.xml”);                <Level levelIndex="1">
                                                            <Level levelIndex="1">
                                                              <ImagePath>Girl.jpg</ImagePath>
                                                              <ImagePath>Boy.jpg</ImagePath>
foreach ( XElement x in XDoc.Descendants(“Levels”) )          <Rows>3</Rows>
{
                                                              <Rows>3</Rows>
                                                              <Cols>3</Cols>
                                                              <Cols>3</Cols>
    if ( x.Attribute.Value.ToString().Equals(“1”) )
              x.Element(“ImagePath”) = “Boy.jpg”;
                                                            </Level>
                                                            </Level>
}                                                          </Levels>
                                                           </Levels>
XDoc. Save(“GameData.xml”);

Tương tự với các thành phần khác của <Level levelIndex="1“> _</Levels>
Như: <Rows> hay <Cols>...

      27                                                                                    SE-PRO
Cập nhật một Element(3)


            • SetValue(object value);
 SetValue   • Đặt giá trị cho element hiện tại giá trị là value vì là kiểu object
              nên nó cũng có thể là cả một XElement.



Tương tự như Properties Value:
 Chỉ cần thay x.Element(“ImagePath”) = “Boy.jpg”;
Bằng x.SetValue(“Boy.jpg”); sẽ cho kết quả ý hệt.




28                                                                           SE-PRO
Cập nhật một Element(3)
                            • SetAttributeValue(XName name, object value);
 SetAttributeValue
                            • Đặt giá trị value cho “attribute” của element tên name.



Muốn cập nhật phải tìm được XElement trong tài liệu trước.


Code:      Thay đổi Attribute của <Level levelIndex="1“>   GameData.xml
using System.Xml.Linq;                                     <? xml version="1.0" encoding="utf-8"?>
                                                           <? xml version="1.0" encoding="utf-8"?>
...                                                        <!--Thông tin mỗi Level trong game-->
                                                           <!--Thông tin mỗi Level trong game-->
XDocument XDoc =                                           <Levels>
                                                           <Levels>
         new XDocument.Load(“GameData.xml”);                <Level levelIndex="1">
                                                            <Level Index=“3">
                                                              <ImagePath>Girl.jpg</ImagePath>
                                                              <ImagePath>Girl.jpg</ImagePath>
foreach ( XElement x in XDoc.Descendants(“Levels”) )          <Rows>3</Rows>
{
                                                              <Rows>3</Rows>
                                                              <Cols>3</Cols>
                                                              <Cols>3</Cols>
    if ( x.Attribute.Value.ToString().Equals(“1”) )
              x.SetAttributeValue( “Index”, 3);
                                                            </Level>
                                                            </Level>
}                                                          </Levels>
                                                           </Levels>
XDoc. Save(“GameData.xml”);



      29                                                                                    SE-PRO
Cập nhật một Element(4)
                              • SetElementValue(XName name, object value);
  SetElementValue             • Đặt giá trị cho “element” tên name giá trị là value vì là kiểu
                                object nên nó cũng có thể là một XElement.

Code:      Thay đổi Element <Level levelIndex="1“>       GameData.xml
using System.Xml.Linq;                                   <? xml version="1.0" encoding="utf-8"?>
                                                         <? xml version="1.0" encoding="utf-8"?>
...                                                      <!--Thông tin mỗi Level trong game-->
                                                         <!--Thông tin mỗi Level trong game-->
XDocument XDoc =                                         <Levels>
                                                         <Levels>
          new Document.Load(“GameData.xml”);              <Level levelIndex="1">
                                                          <Level Index=“3">
                                                            <ImagePath>Girl.jpg</ImagePath>
                                                            <ImagePath>Laydy.jpg</ImagePath>
foreach ( XElement x in XDoc.Descendants(“Levels”) )        <Rows>3</Rows>
                                                            <Rows>5</Rows>
{                                                           <Cols>3</Cols>
  if ( x.Attribute.Value.ToString().Equals(“1”) )           <Cols>5</Cols>
                                                          </Level>
                                                          </Level>
      x.SetElementValue( “Level”,
          new XElement("Level“,                          </Levels>
                                                         </Levels>
               new XAttribute(“levelIndex", 3),
               new XElement("ImagePath", “Laydy.jpg”),
               new XElement("Rows“, 5),
               new XElement("Cols", 5)                    Bạn cũng có thể thay đổi tất cả các
          )                                              thành phần của Element hiện tại bằng
      );                                                 cách tạo một value là một Element mới !
}
XDoc. Save(“GameData.xml”);
      30                                                                                 SE-PRO
Xóa Element(1)

                        • Remove();
         Remove         • Xóa node hiện tại từ element parent
                          của nó.


                        • RemoveAll();
        RemoveAll       • Xóa tất cả các Attribute và Node con
                          của tài liệu XML hoặc element hiện tại.


                        • RemoveAttributes();
     RemoveAttributes
                        • Xóa “attribute” của element hiện tại .


                        • RmoveNode();
      RemoveNodes       • Xóa node con của element hoặc của
                          cả tài liệu XML.




31                                                                  SE-PRO
Xóa Element(2)
                         • Remove();
       Remove
                         • Xóa node hiện tại từ element parent của nó.



Code: Xóa Tag của Level có Attribute == "1“           GameData.xml
using System.Xml.Linq;                                <? xml version="1.0" encoding="utf-8"?>
                                                      <? xml version="1.0" encoding="utf-8"?>
...                                                   <!--Thông tin mỗi Level trong game-->
                                                      <!--Thông tin mỗi Level trong game-->
XDocument XDoc =                                      <Levels>
                                                      <Levels>
         new XDocument.Load(“GameData.xml”);           <Level levelIndex="1">
                                                      <Level levelIndex="1">
                                                         <ImagePath>Girl.jpg</ImagePath>
                                                         <ImagePath>Girl.jpg</ImagePath>
foreach ( XElement x in XDoc.Descendants(“Level”)        <Rows>3</Rows>
{
                                                         <Rows>3</Rows>
                                                         <Cols>3</Cols>
                                                      </Levels>
    if ( x.Attribute.Value.ToString().Equals(“1”) )
              x.Element(“Cols”).Remove();
                                                       </Level>
}                                                     </Levels>
XDoc. Save(“GameData.xml”);




 Sau khi xác định được Level có Attirbute levelIndex == “1” rồi tìm đến Tag
<Cols> ta xóa nó.
      32                                                                               SE-PRO
Xóa Element(3)
                    • RemoveAll();
      RemoveAll     • Xóa tất cả các Attribute và Node con của tài liệu XML hoặc element
                      hiện tại.

Code: Xóa Element Level có Attribute == "1“           GameData.xml
using System.Xml.Linq;                                <? xml version="1.0" encoding="utf-8"?>
...                                                   <!--Thông tin mỗi Level trong game-->
XDocument XDoc =                                      <Levels>
         new XDocument.Load(“GameData.xml”);           <Level levelIndex="1">
                                                         <ImagePath>Girl.jpg</ImagePath>
foreach ( XElement x in XDoc.Descendants(“Level”) )      <Rows>3</Rows>
{                                                        <Cols>3</Cols>
    if ( x.Attribute.Value.ToString().Equals(“1”) )
                                                       </Level>
              x.RemoveAll();
}                                                     </Levels>
XDoc. Save(“GameData.xml”);
                                                      <? xml version="1.0" encoding="utf-8"?>
 Sau khi xác
                                                      <!--Thông tin mỗi Level trong game-->
định được Level           Sau khi xóa, file           <Levels>
có Attirbute              GameData.xml
levelIndex == “1”
                                                      </Levels>
thì xóa nó.
      33                                                                               SE-PRO
Xóa Element(4)
  RemoveAttributes         • RemoveAttributes();
                           • Xóa Attribute của element hiện tại .



Code: Xóa Attribute của Level có Attribute == "1“     GameData.xml
using System.Xml.Linq;                                <? xml version="1.0" encoding="utf-8"?>
                                                      <? xml version="1.0" encoding="utf-8"?>
...                                                   <!--Thông tin mỗi Level trong game-->
                                                      <!--Thông tin mỗi Level trong game-->
                                                      <Levels>
                                                      <Levels>
XDocument XDoc =
                                                       <Level levelIndex="1">
                                                       <Level >
       new
                                                         <ImagePath>Girl.jpg</ImagePath>
                                                         <ImagePath>Girl.jpg</ImagePath>
XDocument.Load(“GameData.xml”);
                                                         <Rows>3</Rows>
                                                         <Rows>3</Rows>
                                                         <Cols>3</Cols>
                                                         <Cols>3</Cols>
foreach ( XElement x in
                                                       </Level>
                                                       </Level>
XDoc.Descendants(“Level”) )
                                                      </Levels>
                                                      </Levels>
{
    if ( x.Attribute.Value.ToString().Equals(“1”) )
            x.RemoveAttribute();                       Sau khi xác định được Level có
}                                                     Attirbute levelIndex == “1” thì xóa
XDoc. Save(“GameData.xml”);                           Attribute nó.


      34                                                                                SE-PRO
Xóa Element(5)
                          • RmoveNode();
      RemoveNodes         • Xóa node con của một XElement hoặc của tài liệu
                            XML(XDocument).


Code: Xóa Tag <Size> của Level có Attribute == "1“    GameData.xml
using System.Xml.Linq;                                <? xml version="1.0" encoding="utf-8"?>
                                                      <? xml version="1.0" encoding="utf-8"?>
                                                      <!--Thông tin mỗi Level trong game-->
                                                      <!--Thông tin mỗi Level trong game-->
...                                                   <Levels>
XDocument XDoc =                                      <Levels>
                                                       <Level >
                                                       <Level >
       new                                               <ImagePath>Girl.jpg</ImagePath>
XDocument.Load(“GameData.xml”);                          <ImagePath>Girl.jpg</ImagePath>
                                                         <Size>
                                                      </Level>
                                                           <Rows>3</Rows>
                                                      </Levels>
foreach ( XElement x in                                    <Cols>3</Cols>
XDoc.Descendants(“Level”) )                             </Size>
{                                                      </Level>
    if ( x.Attribute.Value.ToString().Equals(“1”) )   </Levels>
            x.Element(“Size”).RemoveNodes();
}                                                      Sau khi xác định được Level có
XDoc. Save(“GameData.xml”);                           Attirbute levelIndex == “1” thì xóa
                                                      Node “Size” nó.

      35                                                                               SE-PRO
Nội dung


     Tổng quan về XML và LINQ



         Truy vấn XML bằng LINQ



        Tạo và Biến đổi một tài liệu XML



     Danh sách nhóm và tài liệu tham khảo




36                                          SE-PRO
Danh sách nhóm và tài liệu tham khảo

                    Danh sách thành viên nhóm
  STT           Tên                  MSSV           Lớp
   1       Nguyễn Văn Biên         10520138     WINP1.C24
       2   Nguyễn Văn Thịnh        10520245     WINP1.C25
       3     Lê Ngọc Anh           10520567     WINP1.C24

 Tài liệu tham khảo:

    http://msdn.microsoft.com
    LINQ for Visual C# 2005 – Fabio Claudio Ferracchiati.



  37                                                      SE-PRO
WINP1.C24

Contenu connexe

Tendances

Những thuật ngữ thường gặp trong Reverse Engineering .NET
Những thuật ngữ thường gặp trong Reverse Engineering .NETNhững thuật ngữ thường gặp trong Reverse Engineering .NET
Những thuật ngữ thường gặp trong Reverse Engineering .NETLevis Nickaster
 
Chp5 - Applications Android
Chp5 - Applications AndroidChp5 - Applications Android
Chp5 - Applications AndroidLilia Sfaxi
 
Giáo trình mạng máy tính PTIT
Giáo trình mạng máy tính PTITGiáo trình mạng máy tính PTIT
Giáo trình mạng máy tính PTITNguynMinh294
 
Bài 4: NGÔN NGỮ TRUY VẤN CÓ CẤU TRÚC (SQL)
Bài 4: NGÔN NGỮ TRUY VẤN CÓ CẤU TRÚC (SQL)Bài 4: NGÔN NGỮ TRUY VẤN CÓ CẤU TRÚC (SQL)
Bài 4: NGÔN NGỮ TRUY VẤN CÓ CẤU TRÚC (SQL)MasterCode.vn
 
Tìm hiểu về hệ điều hành android
Tìm hiểu về hệ điều hành androidTìm hiểu về hệ điều hành android
Tìm hiểu về hệ điều hành androidTÓc Đỏ XuÂn
 
Owasp top-10-2013-french
Owasp top-10-2013-frenchOwasp top-10-2013-french
Owasp top-10-2013-frenchvangogue
 
Bài 2 Cài đặt Windows Server 2008 - Giáo trình FPT
Bài 2 Cài đặt Windows Server 2008 - Giáo trình FPTBài 2 Cài đặt Windows Server 2008 - Giáo trình FPT
Bài 2 Cài đặt Windows Server 2008 - Giáo trình FPTMasterCode.vn
 
Lập trình web - HTML cơ bản
Lập trình web - HTML cơ bảnLập trình web - HTML cơ bản
Lập trình web - HTML cơ bảnNhóc Nhóc
 
Bài 7 Xây dựng website - Giáo trình FPT
Bài 7 Xây dựng website - Giáo trình FPTBài 7 Xây dựng website - Giáo trình FPT
Bài 7 Xây dựng website - Giáo trình FPTMasterCode.vn
 
Support du cours : Programmation Web 2
Support du cours : Programmation Web 2Support du cours : Programmation Web 2
Support du cours : Programmation Web 2Faycel Chaoua
 
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPT
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPTBài 1: Làm quen với SQL Server 2008 - Giáo trình FPT
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPTMasterCode.vn
 
Các kỹ thuật bảo trì phần mềm
Các kỹ thuật bảo trì phần mềmCác kỹ thuật bảo trì phần mềm
Các kỹ thuật bảo trì phần mềmNguyễn Anh
 

Tendances (20)

Pilha e Fila Estática
Pilha e Fila EstáticaPilha e Fila Estática
Pilha e Fila Estática
 
Dns
DnsDns
Dns
 
Les framework mvc
Les framework mvcLes framework mvc
Les framework mvc
 
Đề tài: Xây dựng ứng dụng Android nghe nhạc trên internet, HOT
Đề tài: Xây dựng ứng dụng Android nghe nhạc trên internet, HOTĐề tài: Xây dựng ứng dụng Android nghe nhạc trên internet, HOT
Đề tài: Xây dựng ứng dụng Android nghe nhạc trên internet, HOT
 
P5 stockage
P5 stockageP5 stockage
P5 stockage
 
Luận văn: Xây dựng ứng dụng Android nghe nhạc offline, HOT
Luận văn: Xây dựng ứng dụng Android nghe nhạc offline, HOTLuận văn: Xây dựng ứng dụng Android nghe nhạc offline, HOT
Luận văn: Xây dựng ứng dụng Android nghe nhạc offline, HOT
 
400 câu hỏi thi trắc nghiệm ASP.NET có đáp án - Thiết kế website kinh doanh 2
400 câu hỏi thi trắc nghiệm ASP.NET có đáp án - Thiết kế website kinh doanh 2400 câu hỏi thi trắc nghiệm ASP.NET có đáp án - Thiết kế website kinh doanh 2
400 câu hỏi thi trắc nghiệm ASP.NET có đáp án - Thiết kế website kinh doanh 2
 
Những thuật ngữ thường gặp trong Reverse Engineering .NET
Những thuật ngữ thường gặp trong Reverse Engineering .NETNhững thuật ngữ thường gặp trong Reverse Engineering .NET
Những thuật ngữ thường gặp trong Reverse Engineering .NET
 
P4 intents
P4 intentsP4 intents
P4 intents
 
Chp5 - Applications Android
Chp5 - Applications AndroidChp5 - Applications Android
Chp5 - Applications Android
 
Giáo trình mạng máy tính PTIT
Giáo trình mạng máy tính PTITGiáo trình mạng máy tính PTIT
Giáo trình mạng máy tính PTIT
 
Bài 4: NGÔN NGỮ TRUY VẤN CÓ CẤU TRÚC (SQL)
Bài 4: NGÔN NGỮ TRUY VẤN CÓ CẤU TRÚC (SQL)Bài 4: NGÔN NGỮ TRUY VẤN CÓ CẤU TRÚC (SQL)
Bài 4: NGÔN NGỮ TRUY VẤN CÓ CẤU TRÚC (SQL)
 
Tìm hiểu về hệ điều hành android
Tìm hiểu về hệ điều hành androidTìm hiểu về hệ điều hành android
Tìm hiểu về hệ điều hành android
 
Owasp top-10-2013-french
Owasp top-10-2013-frenchOwasp top-10-2013-french
Owasp top-10-2013-french
 
Bài 2 Cài đặt Windows Server 2008 - Giáo trình FPT
Bài 2 Cài đặt Windows Server 2008 - Giáo trình FPTBài 2 Cài đặt Windows Server 2008 - Giáo trình FPT
Bài 2 Cài đặt Windows Server 2008 - Giáo trình FPT
 
Lập trình web - HTML cơ bản
Lập trình web - HTML cơ bảnLập trình web - HTML cơ bản
Lập trình web - HTML cơ bản
 
Bài 7 Xây dựng website - Giáo trình FPT
Bài 7 Xây dựng website - Giáo trình FPTBài 7 Xây dựng website - Giáo trình FPT
Bài 7 Xây dựng website - Giáo trình FPT
 
Support du cours : Programmation Web 2
Support du cours : Programmation Web 2Support du cours : Programmation Web 2
Support du cours : Programmation Web 2
 
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPT
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPTBài 1: Làm quen với SQL Server 2008 - Giáo trình FPT
Bài 1: Làm quen với SQL Server 2008 - Giáo trình FPT
 
Các kỹ thuật bảo trì phần mềm
Các kỹ thuật bảo trì phần mềmCác kỹ thuật bảo trì phần mềm
Các kỹ thuật bảo trì phần mềm
 

En vedette

Tai lieu-xml
Tai lieu-xmlTai lieu-xml
Tai lieu-xmlanhcubin
 
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ụngDuy Lê Văn
 
template magento
template magentotemplate magento
template magentodvms
 
Program Global Forum 2009
Program Global Forum 2009Program Global Forum 2009
Program Global Forum 2009guestc90ea4a
 

En vedette (7)

Tai lieu-xml
Tai lieu-xmlTai lieu-xml
Tai lieu-xml
 
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
 
Barrier
BarrierBarrier
Barrier
 
Chapter 4 xml schema
Chapter 4   xml schemaChapter 4   xml schema
Chapter 4 xml schema
 
Photos Cuba Go
Photos Cuba GoPhotos Cuba Go
Photos Cuba Go
 
template magento
template magentotemplate magento
template magento
 
Program Global Forum 2009
Program Global Forum 2009Program Global Forum 2009
Program Global Forum 2009
 

Similaire à LINQ TO XML

Kiến thức cần thiết làm việc
Kiến thức cần thiết làm việcKiến thức cần thiết làm việc
Kiến thức cần thiết làm việcmanhvokiem
 
Linq n hibernate net-tier
Linq n hibernate net-tierLinq n hibernate net-tier
Linq n hibernate net-tierNguyen Tran
 
Bài thuyết trình môn công nghệ web
Bài thuyết trình môn công nghệ webBài thuyết trình môn công nghệ web
Bài thuyết trình môn công nghệ webTony Huynh
 
11 building joomla! extensions with flex integration
11 building joomla! extensions with flex integration11 building joomla! extensions with flex integration
11 building joomla! extensions with flex integrationNguyen Duc Phu
 
Laravel
LaravelLaravel
LaravelHoc Vu
 
ứNg dụng xml
ứNg dụng xmlứNg dụng xml
ứNg dụng xmlSon Nguyen
 
Hệ thống quản lý và phân tích log tập trung elk stack
Hệ thống quản lý và phân tích log tập trung elk stackHệ thống quản lý và phân tích log tập trung elk stack
Hệ thống quản lý và phân tích log tập trung elk stacklaonap166
 
1 giới thiệu-cài đặt oracle
1 giới thiệu-cài đặt oracle1 giới thiệu-cài đặt oracle
1 giới thiệu-cài đặt oraclehoangdinhhanh88
 
Silverlight chapter 1
Silverlight chapter 1Silverlight chapter 1
Silverlight chapter 1hthuyet
 
ADO .NET Entity framework
ADO .NET Entity frameworkADO .NET Entity framework
ADO .NET Entity frameworkMinh Tri Lam
 
Bài 2: J2EE - Lập Trình Mạng Nâng Cao
Bài 2: J2EE - Lập Trình Mạng Nâng CaoBài 2: J2EE - Lập Trình Mạng Nâng Cao
Bài 2: J2EE - Lập Trình Mạng Nâng CaoTuan Nguyen
 
16 ldap server
16  ldap server16  ldap server
16 ldap serverCơn Gió
 
Bai 1 lam quen voi sql 2008
Bai 1 lam quen voi sql 2008Bai 1 lam quen voi sql 2008
Bai 1 lam quen voi sql 2008Phương Nhung
 

Similaire à LINQ TO XML (20)

Kiến thức cần thiết làm việc
Kiến thức cần thiết làm việcKiến thức cần thiết làm việc
Kiến thức cần thiết làm việc
 
LinQ
LinQLinQ
LinQ
 
Linq n hibernate net-tier
Linq n hibernate net-tierLinq n hibernate net-tier
Linq n hibernate net-tier
 
Asp.net 3.5 _1
Asp.net 3.5 _1Asp.net 3.5 _1
Asp.net 3.5 _1
 
Bài thuyết trình môn công nghệ web
Bài thuyết trình môn công nghệ webBài thuyết trình môn công nghệ web
Bài thuyết trình môn công nghệ web
 
11 building joomla! extensions with flex integration
11 building joomla! extensions with flex integration11 building joomla! extensions with flex integration
11 building joomla! extensions with flex integration
 
Laravel
LaravelLaravel
Laravel
 
ứNg dụng xml
ứNg dụng xmlứNg dụng xml
ứNg dụng xml
 
Hệ thống quản lý và phân tích log tập trung elk stack
Hệ thống quản lý và phân tích log tập trung elk stackHệ thống quản lý và phân tích log tập trung elk stack
Hệ thống quản lý và phân tích log tập trung elk stack
 
1 giới thiệu-cài đặt oracle
1 giới thiệu-cài đặt oracle1 giới thiệu-cài đặt oracle
1 giới thiệu-cài đặt oracle
 
Silverlight chapter 1
Silverlight chapter 1Silverlight chapter 1
Silverlight chapter 1
 
On thi kpdl
On thi kpdlOn thi kpdl
On thi kpdl
 
ADO .NET Entity framework
ADO .NET Entity frameworkADO .NET Entity framework
ADO .NET Entity framework
 
Bài 2: J2EE - Lập Trình Mạng Nâng Cao
Bài 2: J2EE - Lập Trình Mạng Nâng CaoBài 2: J2EE - Lập Trình Mạng Nâng Cao
Bài 2: J2EE - Lập Trình Mạng Nâng Cao
 
Sof301 slide1
Sof301   slide1Sof301   slide1
Sof301 slide1
 
16 ldap server
16  ldap server16  ldap server
16 ldap server
 
Introduction Vs2008 Dot Net35
Introduction Vs2008 Dot Net35Introduction Vs2008 Dot Net35
Introduction Vs2008 Dot Net35
 
Bai 1 lam quen voi sql 2008
Bai 1 lam quen voi sql 2008Bai 1 lam quen voi sql 2008
Bai 1 lam quen voi sql 2008
 
Thutap
ThutapThutap
Thutap
 
Asp control
Asp controlAsp control
Asp control
 

LINQ TO XML

  • 1. LINQ TO XML .NET 4.0 WINP1.C24
  • 2. Nội dung Tổng quan về XML và LINQ Truy vấn XML bằng LINQ Tạo và Biến đổi một tài liệu XML Danh sách nhóm và tài liệu tham khảo 2 SE-PRO
  • 3. Tổng quan về XML và LINQ 3 SE-PRO
  • 4. Tổng quan về XML và LINQ Lịch sử hình thành 2005 1986 XML v6.0  SGML ( Standard 1996 Generalized Markup Language) ra đời.  Rắc rối, không  XML (eXtensible thích hợp cho việc 1991 Markup truyền tải thông tin Language)version 1.0 ra đời giải quyết được các nhược  HTML (Hyper Text Markup điểm trên Language) ra đời. Chú trọng đến việc hiển thị thông tin hơn là truyền tải, còn nhiều nhược điểm 4 SE-PRO
  • 5. Tổng quan về XML và LINQ •  Thiết kế nhằm trình bày dữ c nhau liệu.  • Mô tả u o  thông tin • thông tin 5 SE-PRO
  • 6. Tổng quan về XML và LINQ XML đang thay đổi web như thế nào? Đơn giản hóa việc Cho phép mã hóa Cho phép tìm kiếm trao đổi dữ liệu thông minh thông minh 6 SE-PRO
  • 7. Các thành phần của một file xml Bảng mã lưu Phần GameData.xml khai báo <? xml version="1.0" encoding="utf-8“ standalone = "yes“ ?> <!--Thông tin Level --> Chú thích Thẻ <Levels> bắt đầu <Level levelIndex="1"> <ImagePath>Girl.jpg</ImagePath> Một <Rows>3</Rows> Phần <Cols>3</Cols> Element thân </Level> của <Level levelIndex=“2“ > tài <ImagePath>Lady.jpg</ImagePath> Attribute liệu <Rows>4</Rows> <Cols>4</Cols> Một Tag </Level> </Levels> Thẻ kết thúc 7 SE-PRO
  • 8. Giới thiệu về LINQ LINQ (Language Integrated Query) – Ngôn ngữ truy vấn tích hợp - Ngôn ngữ thống nhất cách thức truy xuất dữ liệu trong .NET. Được phát triển từ năm 2003, và được công bố tại Hội nghị Microsoft Professional Developers vào 2005 do Anders Hejlsberg và nhóm của ông đã trình bày. Được tích hợp sẵn trong Visual Studio 2008 (.NET 3.5). 8 SE-PRO
  • 9. Giới thiệu về LINQ • LINQ được phân thành 3 loại: LINQ to Objects LINQ to XML LINQ to SQL • Lợi ích sử dụng LINQ  Nó cung cấp một cách chung để truy xuất dữ liệu từ bất kỳ nguồn nào với cùng một cú pháp.  Giúp thực hiện truy vấn một cách dễ dàng hơn.  Được tích hợp như cú pháp của ngôn ngữ lập trình. 9 SE-PRO
  • 10. Nội dung Tổng quan về XML và LINQ Truy vấn XML bằng LINQ Tạo và Biến đổi một tài liệu XML Danh sách nhóm và tài liệu tham khảo 10 SE-PRO
  • 11. LINQ TO XML(1)  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). Tuy nhiên 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.  LINQ to XML có cấu trúc truy vấn tương tự SQL.  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 11 SE-PRO
  • 12. LINQ TO XML(2)  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. 12 SE-PRO
  • 13. Truy vấn XML bằng LINQ(1)  IEnumerable<XElement> Descendants( string ElementName)  Trả ra một Collections XElement giúp bạn truy xuất đến Element có tên ElementName.  IEnumerable<XElement> Ancestor();  Trả ra một Collections các XElement chứa nó (parent).  IEnumerable<XElement> ElementBeforeSelf();  Trả ra một Collections các XElement đứng trước Element hiện tại.  IEnumerable<XElement> ElementAfterSelf();  Trả ra một Collections các XElement đứng sau Element hiện tại. 13 SE-PRO
  • 14. Truy vấn XML bằng LINQ(2) XElement Parent();  Trả ra một XElement giúp bạn truy xuất đến Element cha(chứa nó). bool HasElement();  Kiểm tra xem Element hiện tại có Element con nào không. bool HasAttribute();  Kiểm tra xem Element hiện tại có Attribute nào không. void Save( string URL);  Lưu một tài liệu XML xuống file URL bool IsEmpty();  Kiểm tra xem Element hiện tại có rỗng không. 14 SE-PRO
  • 15. Truy vấn XML bằng LINQ(4) Ba phần cơ bản của một truy vấn XML 1. Có được các dữ liệu nguồn. Lấy nội dung tag Rows của 2. Tạo các truy vấn. Element có levelIndex == 2 3. Thực hiện các truy vấn. using System.Xml.Linq; GameData.xml ... <? xml version="1.0" encoding="utf-8"?> XDocument XDoc = new <!--Thông tin Level --> XDocument.Load(“GameData.xml”); <Levels> <Level levelIndex="1"> var query = from q in <ImagePath>Girl.jpg</ImagePath> XDoc.Descendants(“Levels”).Elements(“Level”) <Rows>3</Rows> where (int)q.XAttribute(“levelIndex”) == 2 <Cols>3</Cols> select q; </Level> <Level levelIndex=“2"> foreach( var p in query) <ImagePath>Boy.jpg</ImagePath> { <Rows>4</Rows> System.Console.WriteLine(“Rows: {0}”, <Cols>4</Cols> p.Element(“Rows”).Value); </Level> } </Levels> 15 SE-PRO
  • 16. Nội dung Tổng quan về XML và LINQ Truy vấn XML bằng LINQ Tạo và Biến đổi một tài liệu XML Danh sách nhóm và tài liệu tham khảo 16 SE-PRO
  • 17. Tạo và Biến đổi một tài liệu XML Tạo một tài liệu XML: Ta sử dụng hàm khởi tạo XDocument(); XDocument(XDeclaration xd, param object[] content); Trong đó:  XDeclaration(string version, string encoding, string standalone) version là phiên bản của tài liệu “1.0”. encoding là bảng mã lữu trữ “UTF-8”. standalone tồn tại một mình hay không “Yes” hoặc “No”. Thường thì không có thuộc tính này cũng không xao cả.  object[] là danh sách các đối tượng cần đưa vào tài liệu:  XComment(string comment ) Chứa chú thích cho tài liệu comment = “Chú thích đây” sẽ cho kết quả <!-- Chú thích đây --!>  XElement( XName name, param object[] content) • XName là tên của Element <name> </name> •object[] tương tự object[] nói ở trên.  Dùng hàm Save( string URL ) để lưu xuống file URL 17 SE-PRO
  • 18. Tạo và Biến đổi một tài liệu XML Tạo một tài liệu XML: Code: GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin Level --> <Levels> XDocument XDoc = new XDocument( <Level levelIndex="1"> ( <ImagePath>Girl.jpg</ImagePath> new XDeclaration("1.0", "utf-8”), <Rows>3</Rows> new XComment("Thông tin Level "), <Cols>3</Cols> new XElement(“Level", </Level> new XAttribute(“levelIndex“,1), </Levels> new XElement("ImagePath", “Girl.jpg”), new XElement("Rows", 3), new XElement(“Cols", 3), ); XDoc. Save(“GameData.xml”); 18 SE-PRO
  • 19. Tạo và Biến đổi một tài liệu XML Hoặc táo bạo hơn một chút với phương thức Parse() Code: GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin Level --> <Levels> XDocument XDoc = new XDocument( <Level levelIndex="1"> new XDeclaration("1.0", "utf-8", "yes"), <ImagePath>Girl.jpg</ImagePath> new XComment("Thông tin Level "), <Rows>3</Rows> new XElement.Parse( <Cols>3</Cols> “<Levels> </Level> <Level levelIndex="1"> </Levels> <ImagePath>Girl.jpg</ImagePath> <Rows>3</Rows> <Cols>3</Cols> </Level> </Levels>” ) ); XDoc. Save(“GameData.xml”); 19 SE-PRO
  • 20. Thêm một Element(1) • void Add( XElement content); Add • Thêm content như là một Node con vào đầu Element hiện tại. • void AddFist( XElement content); AddFist • Thêm content như là một Node con vào cuối Element hiện tại. • void AddAfterSelf( XElement content); AddAfterSelf • Chèn một element vào sau element hiện tại • void AddBeforeSelf( XElement content); AddBeforeSelf • Chèn một element vào trước element hiện tại 20 SE-PRO
  • 21. Thêm một Element(2) • void Add( XElement content); Add • Thêm content như là một Node con vào cuối Element hiện tại. Code: Add một XElement vào trong <Levels>_</Levels> GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> <Levels> XDocument XDoc = <Level levelIndex="1"> <Level levelIndex="1"> new XDocument.Load(“GameData.xml”); <ImagePath>Girl.jpg</ImagePath> <ImagePath>Girl.jpg</ImagePath> <Rows>3</Rows> <Rows>3</Rows> XDoc.Element ("Levels“).Add( <Cols>3</Cols> <Cols>3</Cols> new XElement( </Level> </Level> "Level“, </Levels> <Level levelIndex=“2"> new XAttribute(“levelIndex", 2), new XElement("ImagePath", “Laydy.jpg”), <ImagePath>Lady.jpg</ImagePath> new XElement("Rows“, 3), <Rows>3</Rows> new XElement("Cols", 4) <Cols>4</Cols> ) </Level> ); </Levels> XDoc. Save(“GameData.xml”); XDoc.Add(.......); Error !  Vị trí cần chèn vào không phải là một XElement 21 SE-PRO
  • 22. Thêm một Element(3) • void AddFist( XElement content); AddFist • Thêm content như là một Node con vào đầu Element hiện tại. Code: Add một XElement vào trong <Levels>_</Levels> GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> <!--Thông tin mỗi Level trong game--> ... <Levels> XDocument XDoc = <Level levelIndex="1"> <Level levelIndex=“2"> new XDocument.Load(“GameData.xml”); <ImagePath>Girl.jpg</ImagePath> <ImagePath>Lady.jpg</ImagePath> <Rows>3</Rows> <Rows>3</Rows> XDoc.Element ("Levels“).AddFirst( <Cols>3</Cols> <Cols>4</Cols> new XElement( </Level> </Level> "Level“, </Levels> <Level levelIndex="1"> new XAttribute(“levelIndex", 2), <ImagePath>Girl.jpg</ImagePath> new XElement("ImagePath", “Laydy.jpg”), <Rows>3</Rows> new XElement("Rows“, 3), <Cols>3</Cols> new XElement("Cols", 4) </Level> ) </Levels> ); XDoc. Save(“GameData.xml”);  XDoc.Add(.......); Error !  Vị trí cần chèn vào không phải là một XElement. 22 SE-PRO
  • 23. Thêm một Element(4) • void AddAfterSelf( XElement content); AddAfterSelf • Chèn một element vào sau element hiện tại Code: Add một XElement sau <Level levelIndex="1“> GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> XDocument XDoc = <Levels> <Level levelIndex="1"> <Level levelIndex="1"> new XDocument.Load(“GameData.xml”); <ImagePath>Girl.jpg</ImagePath> <ImagePath>Girl.jpg</ImagePath> <Rows>3</Rows> <Rows>3</Rows> XDoc.Descendants(“Levels”).Elements <Cols>3</Cols> <Cols>3</Cols> ("Level“).Last().AddAfterSelf( </Level> </Level> new XElement( </Levels> <Level levelIndex=“2"> "Level“, new XAttribute(“levelIndex", 2), <ImagePath>Lady.jpg</ImagePath> new XElement("ImagePath", “Laydy.jpg”), <Rows>3</Rows> new XElement("Rows“, 3), <Cols>4</Cols> new XElement("Cols", 4) </Level> ) </Levels> ); XDoc. Save(“GameData.xml”); 23 SE-PRO
  • 24. Thêm một Element(5) • void AddBeforeSelf( XElement content); AddBeforeSelf • Chèn một element vào trước element hiện tại Code: Add một XElement trước <Level levelIndex="1“> GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> XDocument XDoc = <Levels> <Level levelIndex="1"> <Level levelIndex=“2"> new XDocument.Load(“GameData.xml”); <ImagePath>Girl.jpg</ImagePath> <ImagePath>Lady.jpg</ImagePath> <Rows>3</Rows> <Rows>3</Rows> XDoc.Descendants(“Levels”).Elements <Cols>3</Cols> <Cols>4</Cols> ("Level“).Last().AddBeforeSelf( </Level> </Level> new XElement( </Levels> <Level levelIndex="1"> "Level“, new XAttribute(“levelIndex", 2), <ImagePath>Girl.jpg</ImagePath> new XElement("ImagePath", “Laydy.jpg”), <Rows>3</Rows> new XElement("Rows“, 3), <Cols>3</Cols> new XElement("Cols", 4) </Level> ) </Levels> ); XDoc. Save(“GameData.xml”); 24 SE-PRO
  • 25. Thêm một Element(6) Kết luận:  Trong hai 4 ví dụ trên thì hai hàm Add() và AddAfterSelf() cho cùng một kết quả chỉ khác nhau ở vị trí Add vào: o XDoc.Element ("Levels“).Add() o XDoc.Descendants(“Levels”).Elements ("Level“).Last().AddAfterSelf()  Tương tự với hai hàm AddFirst() và AddBeforeSelf(). 25 SE-PRO
  • 26. Cập nhật một Element(1) • VD: XElement XE; XE.Value = “123”; Value • Một dạng Properties giúp đặt giá trị cho một element một cách trực tiếp. • SetValue(object value); SetValue • Đặt giá trị cho element hiện tại giá trị là value vì là kiểu object nên nó cũng có thể là cả một XElement. • SetAttributeValue(XName name, object value); SetAttributeValue • Đặt giá trị value cho “attribute” của element tên name. • SetElementValue(XName name, object value); SetElementValue • Đặt giá trị cho “element” tên name giá trị là value vì là kiểu object nên nó cũng có thể là một XElement. 26 SE-PRO
  • 27. Cập nhật một Element(2) • VD: XElement XE; XE.Value = “123”; Value • Một dạng Properties giúp đặt giá trị cho một element một cách trực tiếp. Muốn cập nhật phải tìm được XElement trong tài liệu trước. Code: Thay đổi ImagePath của <Level levelIndex="1“> GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> <!--Thông tin mỗi Level trong game--> XDocument XDoc = <Levels> <Levels> new XDocument.Load(“GameData.xml”); <Level levelIndex="1"> <Level levelIndex="1"> <ImagePath>Girl.jpg</ImagePath> <ImagePath>Boy.jpg</ImagePath> foreach ( XElement x in XDoc.Descendants(“Levels”) ) <Rows>3</Rows> { <Rows>3</Rows> <Cols>3</Cols> <Cols>3</Cols> if ( x.Attribute.Value.ToString().Equals(“1”) ) x.Element(“ImagePath”) = “Boy.jpg”; </Level> </Level> } </Levels> </Levels> XDoc. Save(“GameData.xml”); Tương tự với các thành phần khác của <Level levelIndex="1“> _</Levels> Như: <Rows> hay <Cols>... 27 SE-PRO
  • 28. Cập nhật một Element(3) • SetValue(object value); SetValue • Đặt giá trị cho element hiện tại giá trị là value vì là kiểu object nên nó cũng có thể là cả một XElement. Tương tự như Properties Value:  Chỉ cần thay x.Element(“ImagePath”) = “Boy.jpg”; Bằng x.SetValue(“Boy.jpg”); sẽ cho kết quả ý hệt. 28 SE-PRO
  • 29. Cập nhật một Element(3) • SetAttributeValue(XName name, object value); SetAttributeValue • Đặt giá trị value cho “attribute” của element tên name. Muốn cập nhật phải tìm được XElement trong tài liệu trước. Code: Thay đổi Attribute của <Level levelIndex="1“> GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> <!--Thông tin mỗi Level trong game--> XDocument XDoc = <Levels> <Levels> new XDocument.Load(“GameData.xml”); <Level levelIndex="1"> <Level Index=“3"> <ImagePath>Girl.jpg</ImagePath> <ImagePath>Girl.jpg</ImagePath> foreach ( XElement x in XDoc.Descendants(“Levels”) ) <Rows>3</Rows> { <Rows>3</Rows> <Cols>3</Cols> <Cols>3</Cols> if ( x.Attribute.Value.ToString().Equals(“1”) ) x.SetAttributeValue( “Index”, 3); </Level> </Level> } </Levels> </Levels> XDoc. Save(“GameData.xml”); 29 SE-PRO
  • 30. Cập nhật một Element(4) • SetElementValue(XName name, object value); SetElementValue • Đặt giá trị cho “element” tên name giá trị là value vì là kiểu object nên nó cũng có thể là một XElement. Code: Thay đổi Element <Level levelIndex="1“> GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> <!--Thông tin mỗi Level trong game--> XDocument XDoc = <Levels> <Levels> new Document.Load(“GameData.xml”); <Level levelIndex="1"> <Level Index=“3"> <ImagePath>Girl.jpg</ImagePath> <ImagePath>Laydy.jpg</ImagePath> foreach ( XElement x in XDoc.Descendants(“Levels”) ) <Rows>3</Rows> <Rows>5</Rows> { <Cols>3</Cols> if ( x.Attribute.Value.ToString().Equals(“1”) ) <Cols>5</Cols> </Level> </Level> x.SetElementValue( “Level”, new XElement("Level“, </Levels> </Levels> new XAttribute(“levelIndex", 3), new XElement("ImagePath", “Laydy.jpg”), new XElement("Rows“, 5), new XElement("Cols", 5)  Bạn cũng có thể thay đổi tất cả các ) thành phần của Element hiện tại bằng ); cách tạo một value là một Element mới ! } XDoc. Save(“GameData.xml”); 30 SE-PRO
  • 31. Xóa Element(1) • Remove(); Remove • Xóa node hiện tại từ element parent của nó. • RemoveAll(); RemoveAll • Xóa tất cả các Attribute và Node con của tài liệu XML hoặc element hiện tại. • RemoveAttributes(); RemoveAttributes • Xóa “attribute” của element hiện tại . • RmoveNode(); RemoveNodes • Xóa node con của element hoặc của cả tài liệu XML. 31 SE-PRO
  • 32. Xóa Element(2) • Remove(); Remove • Xóa node hiện tại từ element parent của nó. Code: Xóa Tag của Level có Attribute == "1“ GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> <!--Thông tin mỗi Level trong game--> XDocument XDoc = <Levels> <Levels> new XDocument.Load(“GameData.xml”); <Level levelIndex="1"> <Level levelIndex="1"> <ImagePath>Girl.jpg</ImagePath> <ImagePath>Girl.jpg</ImagePath> foreach ( XElement x in XDoc.Descendants(“Level”) <Rows>3</Rows> { <Rows>3</Rows> <Cols>3</Cols> </Levels> if ( x.Attribute.Value.ToString().Equals(“1”) ) x.Element(“Cols”).Remove(); </Level> } </Levels> XDoc. Save(“GameData.xml”);  Sau khi xác định được Level có Attirbute levelIndex == “1” rồi tìm đến Tag <Cols> ta xóa nó. 32 SE-PRO
  • 33. Xóa Element(3) • RemoveAll(); RemoveAll • Xóa tất cả các Attribute và Node con của tài liệu XML hoặc element hiện tại. Code: Xóa Element Level có Attribute == "1“ GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> XDocument XDoc = <Levels> new XDocument.Load(“GameData.xml”); <Level levelIndex="1"> <ImagePath>Girl.jpg</ImagePath> foreach ( XElement x in XDoc.Descendants(“Level”) ) <Rows>3</Rows> { <Cols>3</Cols> if ( x.Attribute.Value.ToString().Equals(“1”) ) </Level> x.RemoveAll(); } </Levels> XDoc. Save(“GameData.xml”); <? xml version="1.0" encoding="utf-8"?>  Sau khi xác <!--Thông tin mỗi Level trong game--> định được Level Sau khi xóa, file <Levels> có Attirbute GameData.xml levelIndex == “1” </Levels> thì xóa nó. 33 SE-PRO
  • 34. Xóa Element(4) RemoveAttributes • RemoveAttributes(); • Xóa Attribute của element hiện tại . Code: Xóa Attribute của Level có Attribute == "1“ GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> <? xml version="1.0" encoding="utf-8"?> ... <!--Thông tin mỗi Level trong game--> <!--Thông tin mỗi Level trong game--> <Levels> <Levels> XDocument XDoc = <Level levelIndex="1"> <Level > new <ImagePath>Girl.jpg</ImagePath> <ImagePath>Girl.jpg</ImagePath> XDocument.Load(“GameData.xml”); <Rows>3</Rows> <Rows>3</Rows> <Cols>3</Cols> <Cols>3</Cols> foreach ( XElement x in </Level> </Level> XDoc.Descendants(“Level”) ) </Levels> </Levels> { if ( x.Attribute.Value.ToString().Equals(“1”) ) x.RemoveAttribute();  Sau khi xác định được Level có } Attirbute levelIndex == “1” thì xóa XDoc. Save(“GameData.xml”); Attribute nó. 34 SE-PRO
  • 35. Xóa Element(5) • RmoveNode(); RemoveNodes • Xóa node con của một XElement hoặc của tài liệu XML(XDocument). Code: Xóa Tag <Size> của Level có Attribute == "1“ GameData.xml using System.Xml.Linq; <? xml version="1.0" encoding="utf-8"?> <? xml version="1.0" encoding="utf-8"?> <!--Thông tin mỗi Level trong game--> <!--Thông tin mỗi Level trong game--> ... <Levels> XDocument XDoc = <Levels> <Level > <Level > new <ImagePath>Girl.jpg</ImagePath> XDocument.Load(“GameData.xml”); <ImagePath>Girl.jpg</ImagePath> <Size> </Level> <Rows>3</Rows> </Levels> foreach ( XElement x in <Cols>3</Cols> XDoc.Descendants(“Level”) ) </Size> { </Level> if ( x.Attribute.Value.ToString().Equals(“1”) ) </Levels> x.Element(“Size”).RemoveNodes(); }  Sau khi xác định được Level có XDoc. Save(“GameData.xml”); Attirbute levelIndex == “1” thì xóa Node “Size” nó. 35 SE-PRO
  • 36. Nội dung Tổng quan về XML và LINQ Truy vấn XML bằng LINQ Tạo và Biến đổi một tài liệu XML Danh sách nhóm và tài liệu tham khảo 36 SE-PRO
  • 37. Danh sách nhóm và tài liệu tham khảo Danh sách thành viên nhóm STT Tên MSSV Lớp 1 Nguyễn Văn Biên 10520138 WINP1.C24 2 Nguyễn Văn Thịnh 10520245 WINP1.C25 3 Lê Ngọc Anh 10520567 WINP1.C24  Tài liệu tham khảo:  http://msdn.microsoft.com  LINQ for Visual C# 2005 – Fabio Claudio Ferracchiati. 37 SE-PRO