Лектор: Борислава Палева. Galin Iliev MCT, MCPD, MCSD.NET LINQ to XML.
-
Upload
polly-crawford -
Category
Documents
-
view
239 -
download
3
Transcript of Лектор: Борислава Палева. Galin Iliev MCT, MCPD, MCSD.NET LINQ to XML.
Galin IlievMCT, MCPD, MCSD.NEThttp://www.galcho.com
LINQ to XML
LINQ Architecture
Objects
<book> <title/> <author/> <price/></book>
XMLRelational
LINQ enabled data sources
LINQ To Objects
LINQ To XML
LINQ enabled ADO.NET
VB Others…
LINQ To Entities
LINQ To SQL
LINQ To Datasets
.Net Language Integrated Query (LINQ)
C#
LINQ to XML (XLINQ)
• Declarative construction of XML document
• Support for language integrated queries
• Cleaner, simpler, smaller and faster XML API
XML using DOM
XmlDocument doc = new XmlDocument();XmlElement contacts = doc.CreateElement("contacts");foreach (Customer c in customers) if (c.Country == "USA") { XmlElement e = doc.CreateElement("contact"); XmlElement name = doc.CreateElement("name"); name.InnerText = c.CompanyName; e.AppendChild(name); XmlElement phone = doc.CreateElement("phone"); phone.InnerText = c.Phone; e.AppendChild(phone); contacts.AppendChild(e); }doc.AppendChild(contacts);
Programming XML today
<contacts> <contact> <name>Great Lakes Food</name> <phone>(503) 555-7123</phone> </contact> …</contacts>
Imperative model
Document centric
No integrated queries
Memory intensive
LINQ to XML
XElement contacts = new XElement("contacts", from c in customers where c.Country == "USA" select new XElement("contact", new XElement("name", c.CompanyName), new XElement("phone", c.Phone) ));
Programming XML with LINQ Declarative model
Elementcentric
Integrated queries
Smaller and faster
LINQ to XML (XElement) vs. DOM (XmlElement)
• XElement needn’t be part of a “document” object– An XDocument can be created if needed, but XElements can exist without it
• XElement.Name property doesn’t include a namespace prefixes– LINQ to XML resolves namespaces and prefixes at serialization time
• Leaf elements can be cast directly into dataint age = (int?)xAge; //LINQ to XMLint age = (int?)xAge.InnerText; //DOM
• XElement.ToString() outputs the underlying XML
LINQ Query on LINQ to XML
XElement doc = XElement.Load("customers.xml");
var query = from c in doc.Element("Root").Elements("Customers") where c.Element("FullAddress“).Element("Country")
.Value == "Germany"select c;
foreach (XElement result in query)
Console.WriteLine(result);
<?xml version="1.0"?>
<presentation title="LINQ to XML"> <slide>Agenda</slide>
<slide>LINQ Architecture</slide>
<slide>LINQ to XML (XLINQ)</slide>
<slide>XML using DOM</slide>
<slide>LINQ to XML</slide>
<slide>LINQ to XML (XElement) vs. DOM (XmlElement)</slide>
<slide>LINQ Query on LINQ to XML</slide>
<slide>DEMO</slide> <slide>Transforms with DOM</slide>
<slide>Transforms with LINQ to XML</slide>
<slide>Navigation primitives</slide>
<slide>VB 9.0 Literals</slide>
<slide>LINQ to XSD</slide>
<slide>DEMO</slide>
<slide>Q&A</slide>
</presentation>
Transforms with DOM
//Load the stylesheet.XslTransform xslt = new XslTransform();xslt.Load(stylesheet);
//Load the file to transform.XPathDocument doc = new XPathDocument(filename);
//Create an XmlTextWriter which outputs to the console.XmlTextWriter writer = new XmlTextWriter(Console.Out);
//Transform the file and send the output to the console.
xslt.Transform(doc, null, writer, null);writer.Close();
Transforms with LINQ to XML
XElement element = new XElement("salaried_employees", from e in doc.Descendants("employee")
where e.Attribute("salaried").Value == "true" select new XElement("employee", new XElement(e.Element("name")) ) );
Navigation primitives in LINQ to XML
• Similar to the path axes in XPath 1.0– Nodes() : retrieves all the children– Elements(): retrieves all elements children– Elements(“name”): selects children elem. by
name– Attributes()– Parent()– Descendants()– Etc
LINQ to XML Enhancement for VB Only: XML Literals
• VB can create XElements in memory with XElement constructors, same as in C#
Dim contacts As XElement = _ New XElement("contacts", _ New XElement("contact", _ New XElement("name", “Fred Blogs"), _ New XElement("phone", "206-555-0144", _ New XAttribute("type", "home")), _ New XElement("phone", "425-555-0145", _ New XAttribute("type", "work")), _ New XElement("address", _ New XElement("street1", "123 Main St"), _ New XElement("city", "Mercer Island"), _ New XElement("state", "WA"), _ New XElement("postal", "98040"))))
Creating an XElement from an XML Literal
• Wouldn’t you rather do this?
Dim contacts As XElement = _ <contacts> <contact> <name>Fred Blogs</name> <phone type="home">206-555-0144</phone> <phone type="work">425-555-0145</phone> <address> <street1>123 Main St</street1> <city>Mercer Island</city> <state>WA</state> <postal>98040</postal> </address> </contact> </contacts>
• Compiler converts this to same code as previous slide• No need for line continuation characters within the XML
VB XML Literals Can Contain Expressions Evaluated at Runtime
• Element Value from VariableDim name As XElement = <name><%=someVariable%></name>
• Element Value from Function Call
Dim name As XElement = <name><%=SomeFunction()%></name>
• Attribute Value from Variable
Dim phone as XElement =<phone type=(someVariable)>234-5678</phone>
• Element Name from VariableDim contact as XElement =<contact>
<(someVariable)>Foo</></contact>
Embedding LINQ to XML Query Inside XML Literal
Dim root As XElement = _ <Products> <%= From p In dc.Products _ Select <Product ProductId=<%= p.ProductID %>> <Name><%= p.Name %></Name> <ProductNumber><%= p.ProductNumber %></ProductNumber> </Product> %> </Products>
LINQ to XML Enhancement for VB Only: Late Bound XML
• VB can apply three XPath-style navigational operators to an XElement – Child axis operator: “.”– Descendants axis operator: “…”– Attribute axis operator: “@”
• This makes the syntax simpler than the index-based XElement methods– However, VB applies these operators at runtime using late binding, so their use is not type-safe
Late Bound XML ExampleFor Each Dim phone In contact.phone
Console.WriteLine(CStr(phone.@type))NextConsole.WriteLine(CStr(contacts...<city>(0)))
• … which is equivalent to
For Each Dim phone In Contact.Element("phone")Console.WriteLine(CStr(phone.Attribute("type"))
NextConsole.WriteLine(CStr(contact.Descendants("city")(0))
Schema-Aware LINQ to XML?• Current LINQ to XML release are unaware of XML structure at compile time
– Nodes must be located at run time using indexes, and values must be cast to correct data typestring zip = (string)name.Element(“zip”)
• Microsoft is working toward to construct “strongly typed” XML objectsstring zip = name.zip
• LINQ to XSD – alpha v0.2
<?xml version="1.0"?>
<presentation title="LINQ to XML"> <slide>Agenda</slide> <slide>LINQ Architecture</slide> <slide>LINQ to XML (XLINQ)</slide> <slide>XML using DOM</slide> <slide>LINQ to XML</slide> <slide>LINQ to XML (XElement) vs. DOM (XmlElement)</slide> <slide>LINQ Query on LINQ to XML</slide> <slide>DEMO</slide> <slide>Transforms with DOM</slide> <slide>Transforms with LINQ to XML</slide> <slide>Navigation primitives</slide> <slide>VB 9.0 Literals</slide> <slide>LINQ to XSD</slide>
<slide>DEMO</slide> <slide>Q&A</slide>
</presentation>
Resources
• .NET Language-Integrated Query for XML Data• Microsoft XML Team's WebLog• LINQ Tutorial (In Bulgarian)• LINQ Project Forum