Wednesday, December 10, 2008

Linq to Xml (Code Snippets)

Linq to Xml enables you to query an Xml document using the familiar LINQ syntax. Linq to Xml features and found within System.Xml.Linq namespace.
System.Xml.Linq introduces a series of objects such as XDocument, XElement and XAttributes which makes creating XML document a breeze.

XAttribute
private void btnXElement_Click(object sender, RoutedEventArgs e)
{
XElement xe = new XElement(new XElement("Shalvin",
new XElement("Students",
new XElement("Name", "Shalvin"))));
textBox1.Text = xe.ToString();

}


XElement


using System.Xml.Linq;

private void Form1_Load(object sender, EventArgs e)
{
XElement xml = new XElement("contacts",
new XElement("contact",
new XAttribute("contactId", "2"),
new XElement("firstName", "Shalvin"),
new XElement("lastName", "PD")
),
new XElement("contact",
new XAttribute("contactId", "3"),
new XElement("firstName", "Praseed"),
new XElement("lastName", "Pai")
)
);
textBox1.Text = xml.ToString();
}


XDocument

using System.Xml.Linq;

protected void Page_Load(object sender, EventArgs e)
{
XDocument xd = new XDocument();
XElement contacts =
new XElement("contacts",
new XElement("contact",
new XElement("name", "Shalvin"),
new XElement("Location", "Kochi")
),
new XElement("contact",
new XElement("name", "Viju"),
new XElement("Location", "Trichur")
)
);
xd.Add(contacts);
xd.Save("c:\\Shalvin.xml");
System.Diagnostics.Process.Start("iexplore", "c:\\Shalvin.xml");
}

Output

<?xml version="1.0" encoding="utf-8"?>
<contacts>
<contact contactId="2">
<firstName>Shalvin</firstName>
<lastName>P D</lastName>
</contact>
<contact contactId="3">
<firstName>Praseed</firstName>
<lastName>Pai</lastName>
</contact>
</contacts>

XDocument Parse

private void button3_Click(object sender, RoutedEventArgs e)
{
XDocument xd = XDocument.Parse(@"<contacts>
<contact contactId='2'>
<firstName>Shalvin</firstName>
<lastName>P D</lastName>
</contact>
<contact contactId='3'>
<firstName>Praseed</firstName>
<lastName>Pai</lastName>
</contact>
</contacts>");

textBox1.Text = xd.ToString();

}


Querying an Xml Document














using System.Xml.Linq;
private void Form1_Load(object sender, EventArgs e){
XDocument xmlFile = XDocument.Load("c:\\Shalvin.xml");
var query = from c in xmlFile.Elements("contacts").Elements("contact").Elements("name")

select c;
foreach (XElement nam in query)

{
listBox1.Items.Add(nam);
}

}

Related Blogs
Linq to Objects
Linq to Sql
.Net Working with Xml

1 comment:

  1. Amazing stuff, looks like it will be very useful and thats coming from someone who has to work with SQL every day.

    ReplyDelete