Sunday, April 12, 2009

LINQ (Language Integrated Query) C#: Editing XML Docs the easy way in DotNET Framework 3.5 C#

Ive tried appending XML(at the end of the file) many times, but failed (there
are ways of doing it successfully, but i became very confused).

Im writing a small C# application for myself where i can store information
in a XML file and retreive it.

Learning the way to write XML through C# is quite a uphill task, as there are
many known ways of reading/writing/saving a XML document.

Man there are many many classes like XMLDocument, XMLNode, XMLElement, etc
in the "System.Xml" namespace.

With introduction of LINQ interacting with objects or elements which
contain data(arrays, lists, xml docs, databases) have become very easy.

Although there are many cons claimed at many blogs which ive read.

This was the most easiest way of writing XML using LINQ in C#.







using System.Xml.Linq;
using System;
using System.Xml;
using System.Text;
class NodesAttribs
{
public static void Main()
{
//creating a new XML document with body
XDocument doc =
new XDocument(
new XDeclaration("1.0",
Encoding.UTF8.HeaderName, String.Empty),
new XComment("Xml Document"),
new XElement("catalog",
new XElement("book",
new XAttribute("id", "001"),
new XElement("author", "Dan Brown"))
)
);

//end of a single statement, very lengthy isnt it..LOL...but its easy imagining the end XML doc.

//NOW adding a new ELEMENT: to the above created xml file( doc object)

doc.Element("catalog").Add(new XElement("book",
new XAttribute("id", "002"),
new XElement("author", "John Grisham")));

doc.Save("temp.xml");

)
);



The above code will add an element called "book" with attributes
to root element catalog in that specific XML file.

It will generate the following XML :

No comments:

Post a Comment