I've been meaning to do a writeup of this eventually, but I haven't had time. I'll do a quick condensed version here for you to get started. I really love LINQ and want everyone to start using it =D
First, make sure to add a reference to System.Xml.Linq if you haven't, and make sure it's in your using statements. (I see that you already have, but I'm putting this here for other people's benefit).
The first part of the following code gets all the descendant nodes of the root element in the XML document, then loops through them and prints their values. I used the standard long notation for this.
The second part shows a query to find a specific string in the xml, namely the value of the first descendant node called "body". I used shorthand and a lambda expression for this example.
Here's a sample that can get you started.
C# Program - using System;
-
using System.Linq;
-
using System.Xml.Linq;
-
-
namespace TermsHelper
-
{
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
XDocument doc = XDocument.Load(@"c:\dev\temp.xml");
-
-
//standard notation
-
var data = from x in doc.Root.Descendants()
-
select x;
-
foreach (XElement e in data)
-
Console.WriteLine(e.Value);
-
-
//alternate notation
-
string body = doc.Root.Descendants().Where(x => x.Name == "body").First().Value;
-
-
Console.WriteLine("\nBody: {0}", body);
-
-
//attribute example
-
string attribute = doc.Root.Descendants().Where(x => x.Name == "body").First().Attribute("type").Value;
-
Console.WriteLine("\nAttribute: {0}", attribute);
-
Console.Read();
-
}
-
}
-
}
temp.xml - <?xml version="1.0"?>
-
<note>
-
<to>Tove</to>
-
<from>Jani</from>
-
<heading>Reminder</heading>
-
<body type="text">Don't forget me this weekend!</body>
-
</note>
Expected output when executed - Tove
-
Jani
-
Reminder
-
Don't forget me this weekend!
-
-
Body: Don't forget me this weekend!
-
-
Attribute: text
Good luck.