Monday, March 08, 2010

XML with Linq


System.Xml.Linq namespace provide good way of working with XML you don't need to create a DOM object you can smiply create a object of XElement object and then define you XML and after defining the complete XML you can save this XML by smiply calling Save method of XElement object.

For e.g
If I want to generate one XML through XML.Linq first I need to create an object of XElement for root tag and inside that define the nested object of XElement which will become child elements of the root XElement.

xlElement = new XElement("configuration",
new XElement("configSections",
new XElement("section", new XAttribute("name", "log4net"),
new XAttribute("type", "log4net.Config.Log4 NetConfigurationSectionHandler, log4net"))),
new XElement("log4net", new XAttribute("debug", "true")),
new XElement("appender", new XAttribute ("name", "AppTraceFileAppender"), new XAttribute("type", "log4net.Appender.FileAppender")),
new XElement("param", new XAttribute("name", "File"), new XAttribute
("value", "")));


In this case it will create an XML object with root element as Configuration and inside that we have neseted childs,In above senario we have define attribute of an elements with the help of XAttribute calss.

After defining this simply call xlElement.Save(filePath);

No comments: