You are on page 1of 34

LINQ TO XML

Contents
1. Gii thiu LINQ to XML:............................................................................................. 3 2. Xy dng mt cy XML bng Visual C# 2008: ........................................................... 4 2.1. To mt phn t XML: .......................................................................................... 4 2.2. To mt thuc tnh cho phn t XML: .................................................................. 5 2.3. To ghi ch trong cy XML: ................................................................................. 6 2.4. Xy dng mt cy XML: ....................................................................................... 7 2.5. i tng XDeclaration:........................................................................................ 9 2.6. Phng thc XElement.Save: .............................................................................. 10 2.7. Phng thc XDocument.Save:........................................................................... 11 2.8. Phng thc XElement.Load: ............................................................................. 12 2.9. Phng thc XDocument.Load: .......................................................................... 13 3. XML namespace: ........................................................................................................ 14 3.1. Gii thiu namespace: .......................................................................................... 14 3.2. To mt namespace trong cy XML:................................................................... 15 3.3. iu khin tin t namespace trong cy XML: ................................................... 16 3.4. Vit truy vn LINQ trong namespace: ................................................................. 17 4. Nhng thao tc truy vn c bn trn cy XML: ......................................................... 18 4.1. Tm mt phn t trong cy XML:........................................................................ 18 4.2. Lc phn t trong cy XML: ............................................................................... 19 4.3. Sp xp cc phn t trong cy XML: .................................................................. 21 1

4.4. Kt hai cy XML: ................................................................................................ 22 4.5. Nhm cc phn t trong mt cy XML: .............................................................. 25 5. Nhng thao tc bin i trn cy XML: ..................................................................... 28 5.1. Thm phn t, thuc tnh v nt vo mt cy XML:........................................... 28 5.2. Thay i phn t, thuc tnh v nt ca mt cy XML: ...................................... 30 5.3. Xa phn t, thuc tnh v nt t mt cy XML: ................................................ 33

1. Gii thiu LINQ to XML:


LINQ to XML cung cp mt giao din lp trnh XML. LINQ to XML s dng nhng ngn ng mi nht ca .NET Language Framework v c nng cp, thit k li vi giao din lp trnh XML Document Object Model (DOM). XML c s dng rng ri nh dng d liu trong mt lot cc ng cnh (cc trang web, trong cc tp tin cu hnh, trong cc tp tin Microsoft Office Word, v trong c s d liu). LINQ to XML c cu trc truy vn tng t SQL. Nh pht trin trung bnh c th vit cc truy vn ngn gn, mnh m, vit m t hn nhng c ngha nhiu hn. H c th s dng cc biu thc truy vn t nhiu d liu cc lnh vc ti mt thi im. LINQ to XML cng ging nh Document Object Model (DOM) ch n chuyn cc ti liu XML vo b nh. Bn c th truy vn v sa i cc ti liu, v sau khi bn chnh sa n, bn c th lu n vo mt tp tin hoc xut n ra. Tuy nhin, LINQ to XML khc DOM: N cung cp m hnh i tng mi n gin hn v d thao tc hn lm vic , v l tn dng cc ci tin ngn ng trong Visual C # 2008. Kh nng s dng kt qu truy vn l tham s cho i tng XElement v XAttribute cho php mt phng php mnh m to ra cy XML. Phng php ny, c gi l functional construction, cho php cc nh pht trin d dng chuyn i cy XML t mt hnh dng ny sang hnh dng khc. S dng LINQ to XML bn c th: Load XML t nhiu file hoc lung. Xut XML ra file hoc lung. Truy vn cy XML bng nhng truy vn LINQ. Thao tc cy XML trong b nh. Bin i cy XML t dng ny sang dng khc.

2. Xy dng mt cy XML bng Visual C# 2008:


2.1. To mt phn t XML:
Cu trc

XElement(XName name, object content) XElement(XName name) XName: tn phn t. object: ni dng ca phn t.

V d sau to phn t <Customer>c ni dung Adventure Works.

C#

XElement Works");

new

XElement("Customer",

"Adventure

Console.WriteLine(n);
Xml

<Customer>Adventure Works</Customer>

To phn t rng trng phn ni dung:

C#

XElement n = new XElement("Customer"); Console.WriteLine(n);


Xml

<Customer />
4

2.2. To mt thuc tnh cho phn t XML:


Cu trc XAttribute(XName name, object content)

Tham s:
XName: thuc tnh. object: gi tr ca thuc tnh.

C#

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


Xml

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

2.3. To ghi ch trong cy XML:


To mt phn t gm mt ch thch nh mt nt con

Tn XComment(String)

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

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

2.4. Xy dng mt cy XML:


S dng i tng XDocument xy dng mt cy XML. Thng thng ta c th to ra cy XML vi nt gc XElement.
Name XDocument() Description Initializes a new instance of the XDocument class. Initializes a new instance of the XDocument class with the specified content. Initializes a new instance of the XDocument class from an existing XDocument object. Initializes a new instance of the XDocument class with the specified XDeclaration and content.

XDocument(Object[])

XDocument(XDocument)

XDocument(XDeclaration, Object[])

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

<Root> <Child1>data1</Child1> <Child2>data2</Child2> <Child3>data3</Child3> <Child2>data4</Child2> </Root>

2.5. i tng XDeclaration:


i tng XDeclaration c s dng khai bo XML version, encoding, and c th c hoc khng thuc tnh standalone ca mt ti liu XML.

Cu trc 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>

2.6. Phng thc XElement.Save:


Name Save(String) Description 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>

10

2.7. Phng thc XDocument.Save:


Name Save(String) Description 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>

11

2.8. Phng thc XElement.Load:


Name Load(String) Description 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>

12

2.9. Phng thc XDocument.Load:


Name Load(String) Description 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>

13

3. XML namespace:
3.1. Gii thiu namespace:
XML namespace gip trnh xung t gia cc b phn khc nhau ca mt ti liu XML. khi khai bo mt namespace, bn chn mt tn cc b sao cho n l duy nht. Nhng tin t lm cho ti liu XML sc tch v d hiu hn. Mt trong nhng li th khi s dng LINQ to XML vi C# l n gin ha nhng XML name l loi b nhng th tc m nhng nh pht trin s dng tin t. khi LINQ load hoc parse mt ti liu XML, mi tin t s c x l ph hp vi namespace XML. khi lm vic vi ti liu c namespace, bn thng truy cp namespace thng qua namespace URI, khng thng qua tin t namespace.

14

3.2. To mt namespace trong cy 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>

15

3.3. iu khin tin t namespace trong cy XML:


V d sau khai bo hai tin t namespace. Tn min tin t aw, v www.fourthcoffee.com c tin t fc.
http://www.adventure-works.com

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>

16

3.4. Vit truy vn 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

17

4. Nhng thao tc truy vn c bn trn cy XML:


4.1. Tm mt phn t trong cy XML:
Xt v d sau tm phn t Address c thuc tnh 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> </Address>

18

4.2. Lc phn t trong cy XML:


V d sau lc nhng phn t c phn 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 Child Two Text
19

Child Four Text

20

4.3. Sp xp cc phn t trong cy 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. Kt hai cy XML:


V d sau kt nhng phn t Customer vi nhng phn t Order , v to ra ti liu XML mi gm phn t CompanyName bn 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 customers with a // CustomerID > 'K' XElement custOrd = custOrdDoc.Element("Root"); XElement newCustOrd = new XElement("Root", from c custOrd.Element("Customers").Elements("Customer") join o custOrd.Element("Orders").Elements("Order")
22

for

in in

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. Nhm cc phn t trong mt cy XML:


V d nhm d liu theo loi, sau to ra mt tp tin XML mi, trong phn cp XML theo nhm.

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>

25

<Group ID="A"> <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>

26

</Data> <Data> <Quantity>10</Quantity> <Price>.99</Price> </Data> <Data> <Quantity>8</Quantity> <Price>6.99</Price> </Data> </Group> </Root>

27

5. Nhng thao tc bin i trn cy XML:


5.1. Thm phn t, thuc tnh v nt vo mt cy XML:
Thm nt vo cui cy hoc u cy dng phng thc .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 phn t, thuc tnh v nt ca mt cy XML:


S dng phng thc XAttribute.SetValue thay i gi tr thuc tnh "Att" t"root" thnh"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 dng phng thc XNode.ReplaceWith thay i nt c tn "Child3"c ni dung

"child3 content" thnh "NewChild" ni 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>
Thit lp gi tr ca lp con bng hm 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. Xa phn t, thuc tnh v nt t mt cy XML:


V d sau dng phng thc XElement.RemoveAll xa nhng phn t con v thuc tnh ca mt cy 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 tip theo dng phng thc XElement.RemoveAttributes xa ton b thuc tnh ca mt cy 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>

Dng phng thc XNode.Remove xa mt nt ca cy 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 <Child2>child2 <Child4>child4 <Child5>child5 </Root>

content</Child1> content</Child2> content</Child4> content</Child5>

34

You might also like