Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

LINQ to XML

LINQ to XML is a built-in LINQ data provider that provides a clean programming model to read, construct and write XML data. We can use LINQ to XML to perform LINQ queries over XML. It provides much richer querying support than the low-level XmlReader/XmlWriter API in .NET. It uses less memory and more efficient than the XmlDocument, which is built on Document Object Model(DOM).

 

LINQ to XML allows to write Query Expressions over XML and can be combined with any of the other LINQ providers to create or use XML data as a source or destination format.

LINQ to XML uses very simple model for constructing XML documents. Whether it be XML sources from a stream or file, or XML created dynamically in the code.

Constructing an XML Document using LINQ

The LINQ to XML object model does provides XDocument and XElement classes to construct XML Documents. An XML document can be constructed using XElement like below.

XElement salesOrder =
new XElement("SALESORDER",
      new XElement("SOHEADER",
      new XElement("ORDERID", "990310915"),
      new XElement("SALESREP", "Reliance , Consulting"),
      new XElement("CUSTOMERNAME", "RentACoder"),
      new XElement("CUSTOMERPONUMBER", "99033415"),
      new XElement("SHIPTOADDRESS", "QUIKSILVER INC"),
      new XElement("INVOICEADDRESS", "QUIKSILVER INC") ) ,
new XElement("SOLINES",
      new XElement("ITEMNAME", "2006"),
      new XElement("QUANTITY", "6"),
      new XElement("UNITPRICE", "25")),
new XElement("SOLINES",
      new XElement("ITEMNAME", "2007"),
      new XElement("QUANTITY", "4"),
      new XElement("UNITPRICE", "15")),
new XElement("SOLINES",
      new XElement("ITEMNAME", "2008"),
      new XElement("QUANTITY", "6"),
      new XElement("UNITPRICE", "62"))

In the above code we are creating a root node SALESORDER, which holds SOHEADER, SOLINES(multiple) and SOHEADER ,SOLINES contains leaf level nodes which represent header, line columns respectively.

We can optionally create a XML Document which includes an XML Declaration, Comment, and Processing Instruction using XDocument as shown below

XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("LINQ to XML SalesOrder "),
new XProcessingInstruction("MyApp", "123-44-4444"),
salesOrder);
 

XDeclaration, XComment, XProcessingInstruction classes are used to define xml declaration, xml comments and xml processing instructions respectively. SalesOrder object is an XElement which holds the Salesorder xml. XDocument class is used to represent the xml as a XMLDocument.

Loading Existing XML file into a LINQ

We can load existing XML file into an LINQ in XML tree so that we can read it or manipulate it. LINQ to XML provides multiple input sources, including a file, an XmlReader, a TextReader, or a string.

XElement salesOrder = XElement.Load(@"c:\po.xml"); // to load from a file
XElement  salesOrder = XElement.Load(new XmlTextReader(@"c:\po.xml")); // loading from a XML Text Reader

XElement.Load method is used to load the xml into XElement from any file or TextReader. We can also use Parse method of the XElement to load the xml from a string .

 XElement  salesOrder = XElement.Parse(
@"<SALESORDER>
<SOHEADER>
<ORDERID>140310915</ORDERID>
<SALESREP>GLATMAN, AARON</SALESREP>
<CUSTOMERNAME>Quiksilver America</CUSTOMERNAME>
<CUSTOMERPONUMBER></CUSTOMERPONUMBER>
<SHIPTOADDRESS>QUIKSILVER INC</SHIPTOADDRESS>
<INVOICEADDRESS>QUIKSILVER INC</INVOICEADDRESS>
</SOHEADER>
<SOLINES>
<ITEMNAME>1006</ITEMNAME>
<QUANTITY>3</QUANTITY>
<UNITPRICE>.01999</UNITPRICE>
</SOLINES>
<SOLINES>
<ITEMNAME>1006</ITEMNAME>
<QUANTITY>3</QUANTITY>
<UNITPRICE>.01999</UNITPRICE>
</SOLINES>
</SALESORDER>");
 

Traversing XML

We can navigate the LINQ to XML Object Model to retrieve the  XML elements that we  want to work on.

LINQ to XML provides methods for getting the children of an XElement. Nodes() method is used to get all of the children of an XElement (or XDocument).This returns IEnumerable<object>.

foreach (c in salesOrder .Nodes())
{
Console.WriteLine(c);
}

We can navigate to a particular XElement in a XElement or XDocument by using Element(string name) method as shown below.

XElement header = salesOrder.Element("SOHEADER");
XElement orderid = header.Element("ORDERID");

Header obtains a reference to SOHEADER node and orderid gets the ORDERID of the order.

We can even navigate all the elements of a XElement or XDocument by using the Elements() method. Elements method returns IEnumerable<XElement>.

foreach (XElement x in header.Elements())
{
Label lb=new Label();
lb.Text = x.Name.ToString();
TextBox tb = new TextBox();
tb.Text = x.Value;

form.Controls.Add(new LiteralControl("<tr><td>"));
form.Controls.Add(lb);
form.Controls.Add(new LiteralControl("</td><td>"));
form.Controls.Add(tb);
form.Controls.Add(new LiteralControl("</td></tr>"));
form.Controls.Add(new LiteralControl("<p><p>"));

}
form.Controls.Add(new LiteralControl("</table>"));
form.Controls.Add(new LiteralControl("<table>"));
foreach (XElement lines in salesOrder.Elements("SOLINES"))
{
form.Controls.Add(new LiteralControl("<tr>"));
foreach (XElement x in lines.Elements())
{
Label lb=new Label();
lb.Text = x.Name.ToString();
TextBox tb = new TextBox();
tb.Text = x.Value;

form.Controls.Add(new LiteralControl("<td>"));
form.Controls.Add(lb);
form.Controls.Add(new LiteralControl("</td><td>"));
form.Controls.Add(tb);
form.Controls.Add(new LiteralControl("</td>"));


}
form.Controls.Add(new LiteralControl("</tr>"));
form.Controls.Add(new LiteralControl("</table>"));

}

Manipulating XML in LINQ

LINQ to XML provides a full set of methods for manipulating XML. We can insert, delete, copy, and update XML content.

Inserting XML in LINQ

We can easily add elements to the LINQ to XML object Model easily. To add another SOLINES XElement by using the Add() method:

salesOrder.Add( new XElement("SOLINES",
new XElement("ITEMNAME", "2009"),
new XElement("QUANTITY", "6"),
new XElement("UNITPRICE", "62")));

This code fragment will add the SOLINES XElement as the last child of SALESORDER. The add method can be used with XDocument as follows.

XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("LINQ to XML SalesOrder "),
new XProcessingInstruction("MyApp", "123-44-4444"));

doc.Add(salesOrder);
doc.Add(
new XElement("SOLINES",
new XElement("ITEMNAME", "2010"),
new XElement("QUANTITY", "6"),
new XElement("UNITPRICE", "62"))
)

Deleting XML elements in LINQ

To delete a specific XElement, we need to navigate to the content to delete and call the Remove() method as follows .

salesOrder.Element("SOLINES").Remove();

salesOrder.Element("SOLINES") retrieves the first SOLINES XElement from the SalesOrder.

Remove() also works over an IEnumerable, we can remove all the elements of a single SOLINES as follows.

salesOrder.Element("SOLINES").Elements()Remove();

The above statement removes all the elements from the first SOLINES XElement.

Updating XML in LINQ

To update XML,  navigate to the XElement whose contents to be replaced, and then use the ReplaceNodes() method. In order to change the POID of the SOHEADER XElement of a SalesOrder use the following code.

XElement header = salesOrder.Element("SOHEADER");
XElement orderid = header.Element("ORDERID");
orderid.ReplaceNodes("23456");

Alternatively we can use SetElement() method to change the child XElement node Value of a Parent XElement like below:

XElement header = salesOrder.Element("SOHEADER");
header.SetElementValue("ORDERID", "34567");

This tutorial is written by RELIANCE CONSULTING.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |