Wednesday, April 2, 2014

Super quick Linq to XML

I was trying to figure out how to get started with Linq to XML, and found this article. I figured I'd simplify it even more for myself :)
Imagine we have the following file, saved in c:\contacts.xml
<contacts>
<contact id="1">
<firstName>Orlando</firstName>
<lastName>Karam</lastName>
</contact>
<contact id="2">
<firstName>Lina</firstName>
<lastName>Colli</lastName>
</contact>
</contacts>
view raw contacts.xml hosted with ❤ by GitHub

Then we can access it as follows
XDocument loaded = XDocument.Load(@"C:\contacts.xml");
var contacts = from c in loaded.Descendants("contact")
select new {
id=(int)c.Attribute("id"),
name=(string)c.Element("firstName") +" " +(string)c.Element("lastName"),
};
foreach (var c in contacts)
Console.WriteLine("Contact: id={0}, name = {1}", c.id, c.name);
view raw sample.cs hosted with ❤ by GitHub
Notice:

  • on an XDocument, we can call descendants and pass it an element name, to get all the elements with that name (we can also call the no-args version, and get all descendants)
  • What we're getting is an XElement, on which we can call methods like Element or Attribute
  • We can directly cast an element into a string, and it gets us all the text inside that element
  • We can cast an attribute as a string, or an int (or even a float, double or many other types)

No comments:

Post a Comment