Saturday, February 3, 2007

XML Manipulation the Linq way. Simple and clean

Most often people found that manipulating XML can be quite troublesome. Recently i'd found a very simple way to manipulate XML. Let say i want to create an XML file having this format:


<*musiccollection*>
<*album>
<*Title name="DisneyWorld"*>
<*location*>http://www.artifician.com/mp3/disneyworld.mp3<*/location*>
<*/album*>
<*/musiccollection*>

use this code:

XDocument doc = new XDocument("music.xml");

doc.Add(XElement("MusicCollection",
new XElement("Album", new object[] {
new XElement("Title", new XAttribute("Title", "DisneyWorld")),
new XElement("Location", "http://www.fakeurl.com/mp3/disneyworld.mp3") }));

doc.Save();

that's it, the music.xml has created.

btw, u wish to read it. Let say we want to get the value of "Location" we can use this code:

string location = doc.XElement("MusicCollection").XElement("Album"). XElement("Location").Value;

how about Title's name?

string titlename = doc.XElement("MusicCollection").XElement("Album"). XElement("Title").XAttribute("name").Value;

what if i want to motify the Title's name?

doc.XElement("MusicCollection").XElement("Album"). XElement("Title").XAttribute("name").Value = "Superman";


remove the Title's name?
doc.XElement("MusicCollection").XElement("Album"). XElement("Title").XAttribute("name").Remove();


Xml 's CRUD example enough? btw i am using System.Xml.Linq. To discover more please go to http://msdn2.microsoft.com/en-us/netframework/aa904594.aspx

Please keep updated with VS Orcas this month!

p/s plz don't confuse with the '<*', please imagine it as '<' . The reason i type it as because XML is prohibited

6 comments:

Anonymous said...

Hi Nice Blog. We Offer a wide range of back office and I.T Enabled xml data conversion Which match the high global standards in terms of efficiency and accuracy.

Anonymous said...

Hi there, I begin your blog via Google while searching in requital for earliest grant-in-aid in the course of a generosity raid and your brief looks definitely attractive after me

Anonymous said...

Hi there, I begin your blog via Google while searching throughout first gain representing a callousness rebuke and your momentary looks in point of fact intriguing on me

Anonymous said...

Hi there, I initiate your blog via Google while searching in retribution as a remedy for original sake since a callousness descend upon and your pass on looks damned intriguing in return me

Anonymous said...

Bravo, que palabras..., la idea brillante
http://www.frgporn.com/

tanya

Anonymous said...

top [url=http://www.001casino.com/]casino games[/url] coincide the latest [url=http://www.realcazinoz.com/]realcazinoz[/url] manumitted no deposit reward at the chief [url=http://www.baywatchcasino.com/]online casinos
[/url].