Parsing XML using XDocument

I suspect you’re being stumped by the namespace. Try this:

XDocument doc = XDocument.Load("test.xml");
XNamespace ns = "http://ns.adobe.com/xfdf/";

foreach (XElement element in doc.Root
                                .Element(ns + "fields")
                                .Elements(ns + "field"))
{
    Console.WriteLine("Name: {0}; Value: {1}",
                      (string) element.Attribute("name"),
                      (string) element.Element(ns + "value"));
}

Or to find just the one specific element:

XDocument doc = XDocument.Load("test.xml");
XNamespace ns = "http://ns.adobe.com/xfdf/";
var field = doc.Descendants(ns + "field")
               .Where(x => (string) x.Attribute("name") == "my_cool_id")
               .FirstOrDefault();

if (field != null)
{
    string value = (string) field.Element("value");
    // Use value here
}

Leave a Comment