Linq to XML is the modern approach to programming with XML using any .NET Languages. It provides an in-memory XML programming interface that allows querying XML data using SQL-like queries thereby making developers life easy. It also reduces the code size as compared to the old approach.
In the old approach, one had to start with XMLDocument. Using the XMLDocument, create root XMLElement followed by using helper methods to append or create child elements which involved lot of code writing. Also to read/query XMLDocuments, one had to write XPATH queries to get the required data, the validation of which did not happened at compile time.
Using Linq to XML, life has become very easy with the introduction of simple-to-use XML tree creation objects. Also to get data from XDocument, one just have to use simple SQL-like queries having all the required methods to filter & get the required match data. The code size has reduced drastically, more readable and easy to understand.
In .Net 3.5 a new namespace called System.Xml.Linq contains all the classes for creating XML documents in any required format. Some of its members are as listed:
XAttribute – Represents an XML attribute.
XComment – Represents an XML comment.
XDeclaration - Represents an XML declaration.
XDocument - Represents an XML document.
XElement - Represents an XML element.
XName - Represents the name of the XElement or XAttribute
XNamespace - Represents an XML namespace.
XNode - Represents any XML node within an XML document(e.g.element,comment)
Lets see how to create an entire XML Document tree using a single statement.
XDocument doc =
new XDocument(
new XElement("Customer",
new XElement("FirstName", "Atul"),
new XElement("LastName", "Ashpalia")));
doc.save(@"d:\sample.xml");
File output:
<customer>
<FirstName>Atul</FirstName>
<LastName>Ashpalia</LastName>
</customer>
Now lets load this XML document in XDocument object from sample.xml file. Then retrieve the value of the FirstName and print it.
Note: We can also load the XML Document from a stream.
Code:
// Load from file.
XDocument customer = XDocument.Load(@"d:\sample.xml");
// Query the data and print the FirstName
var q = from c in customer
where c.Element("FirstName")
select c;
foreach (string name in q)
Console.WriteLine("First Name = {0}", name);
As seen above, the code to create XML Document and to query it looks much more simplified and easy compared to what the old approach had to offer us. Enjoy coding.
0 comments
Post a Comment