11

Can I get some help parsing the "my_cool_id" from the following xml using XDocument?

<?xml version="1.0" encoding="UTF-8"?>
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
  <fields>
    <field name="field_name_1">
      <value>12345</value>
    </field>
    <field name="my_cool_id">
      <value>12345</value>
    </field>
    <field name="field_name_2">
      <value>12345</value>
    </field>
    <field name="field_name_3">
      <value>12345</value>
    </field>
  </fields>
</xfdf>
LPL
  • 16,827
  • 6
  • 51
  • 95
strickland
  • 1,943
  • 5
  • 21
  • 40

1 Answers1

38

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
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194