Incandescent Blur

September 1, 2009

XMl in .Net

Filed under: C#, XML — admin @ 3:36 pm

In Many cases we may need to send information across services in XML form.
Some common practice is to create a class as a model and serialize it to XML after assigning values.

Or you can use from a variety of ways in which .Net support XML data, such as Xpath, xdocument, xpathnavigator yada, yada

And then there is Linq XML. namespace System.Linq.Xml;

With Linq to XMl, we can create Xml fragments easily.
The code below shows how to create an Xml fragment from a Dictionary.
assuming resultPair is a Dictionary with values.



XDocument doc = new XDocument(
new XElement("Results",
from myListItem in resultPair
select
new XElement("Pair",
new XElement("Key", myListItem.Key),
new XElement("Value", myListItem.Value)
)
)
);


Now You’ve seen the big chunk, lets break it down!

Now to break it down we can start with the XElement

XElement myVar = new XElement("elementName", "any xml data");

myVar will have the value of “<elementName>any xml data</elementName>”

likewise

XElement myVar = new XElement("elementName1",
new XElement("elementName2", "any xml data")
);

myVar will have the value of “<elementName1>
<elementName2>
any xml data
</elementName2>
</elementName1>”

I’ll Continue on this topic on my next blog.

Powered by WordPress