12

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>
3
  • 2
    What have you tried? what was the expected result of your tries? what didn't work as expected? When you want to parse it what do you wish the result to be? Commented Oct 17, 2011 at 19:59
  • Xpath: //field[@name='my_cool_id']/value/text() Commented Oct 17, 2011 at 20:00
  • @MarcB: I don't think that will work as-is, due to namespaces. Commented Oct 17, 2011 at 20:03

1 Answer 1

39

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.