Professional Documents
Culture Documents
LINQ To XML
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
XElement(XName name, object content) XElement(XName name) XName: tn phn t. object: ni dng ca phn t.
C#
XElement Works");
new
XElement("Customer",
"Adventure
Console.WriteLine(n);
Xml
<Customer>Adventure Works</Customer>
C#
<Customer />
4
Tham s:
XName: thuc tnh. object: gi tr ca thuc tnh.
C#
<Phone Type="Home">555-555-5555</Phone>
Tn XComment(String)
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
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
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
10
C#
XDocument doc = new XDocument( new XElement("Root", new XElement("Child", "content") ) ); doc.Save("Root.xml"); Console.WriteLine(File.ReadAllText("Root.xml"));
Xml
11
C#
XElement xmlTree1 = new XElement("Root", new XElement("Child", "content") ); xmlTree1.Save("Tree.xml"); XElement xmlTree2 = XElement.Load("Tree.xml"); Console.WriteLine(xmlTree2);
12
C#
XElement xmlTree1 = new XElement("Root", new XElement("Child", "content") ); xmlTree1.Save("Tree.xml"); XDocument xmlTree2 = XDocument.Load("Tree.xml"); Console.WriteLine(xmlTree2);
Xml
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
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
15
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
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
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
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
20
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
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
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
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);
28
</Root>
29
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
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);
32
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
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
34