Friday, May 14, 2010

XDocument, Creating XDocument Progamatically

hi,
Just a simple how to, The code below will let you create XML document in Silverlight.
Silver light does not support XmlDocument, but it gives us XDocument with similar functionalities, which is in System.Xml.Linq.  Below is code -

Object[]  xmlNodes = new Object[5];
xmlNodes[1] = new XElement("Person",new XElement("Name","XX"),new XElement("Age","2"));
xmlNodes[2] = new XElement("Person",new XElement("Name","YY"), new XElement("Age","3"));

XDocument xDoc = new XDocument (new XDeclaration("1.0","utf-16","Yes"),new XElement("Root",xmlNodes);

Wow! done The out put is -
<xml version="1.0" coding="utf-16" standalone="yes">
<Root>
<person>
 <name>XX</name>
<age>2</age>
</person>
<person>
<name>YY</name>
<age>22</age>
</person>
</Root>
So what happened actually -
XElement is responsible for creating any node, it takes Node name and value, or object array of values.
XDeclaration is resposible for Xml declaration if
and XDocument is replacement for XmlDocument.
So we create object of XDocument and used Add method to add elements into it.
cheers !!

No comments:

Post a Comment