Functional Construction in LINQ To XML
In this post we describe how we can create XML documents using LINQ to XML.Here we will discuss about functional construction of a XML tree in which we can construct a XML document using a single statement.Before getting into examples let us take a look at the constructors of System.Xml.XLinq.XAttribute class.
public XElement(XName name,Object content) - This constructor takes the name of the element and a content object which can be another XElement or XAttribute as shown below:
XElement po = new XElement("PurchaseOrders",
new XElement("PurchaseOrder"
)
);
Console.WriteLine(po);
Here we are creating a simple document with PurchaseOrder element as child of PurchaseOrders as shown below:
<PurchaseOrders>
<PurchaseOrder />
</PurchaseOrders>
public XElement(XName name,Object[] content) - This constructor is quite similar to the first apart from the fact that it accepts an array of XElement or XAttribute as the content object as shown below:
XElement po = new XElement("PurchaseOrders",
new XElement("PurchaseOrder",
new XAttribute("PODate", "12/31/2008"),
new XAttribute("PONumber", "1111")
)
);
Here we are creating a PurchaseOrder element with two attributes PODate and PONumber as child element of PurchaseOrders.The output will be:
<PurchaseOrders>
<PurchaseOrder PODate="12/31/2008" PONumber="1111" />
</PurchaseOrders>
If we pass an object that implements IEnumerable<T> and type is XElement or XAttribute they are added to each elements are added seperately.We can use a LINQ query to add contents as shown below:
XDocument doc = XDocument.Load("Sample1.xml");
XElement po = new XElement("PurchaseOrders",
from elem in doc.Descendants("PurchaseOrder")
select elem
);
In this context we should also understand the difference between node attaching and cloning.When a node without any parent is added to a tree it is simply attached but one with a parent is deep cloned and then added to the tree.
In our next post we will take a look into advanced features of XLINQ like annotations and event processing.