0

I am trying to get the value of an element using a XML attribute criteria. Essentially I just want one value from the entire document and I've been trying to query it directly. This is my XML file:

<?xml version="1.0" encoding="UTF-8"?>
<list version="1.0">
   <meta>
      <type>resource-list</type>
   </meta>
   <resources start="0" count="1">
      <resource classname="Quote">
         <field name="name">Microsoft Corporation</field> <!-- I want this!!! -->
         <field name="price">49.869999</field>
         <field name="symbol">MSFT</field>
         <field name="ts">1461960000</field>
         <field name="type">equity</field>
         <field name="utctime">2016-04-29T20:00:00+0000</field>
         <field name="volume">48411684</field>
      </resource>
   </resources>
</list>

In particular, I want the field with the "name" attribute in it. This is what I've done to retrieve this:

            XDocument xDoc = XDocument.Parse(httpResponseBody);
            string name = (string)xDoc.Elements("field").First(x => x.Attribute("name").Value == "name");

I get an "element not matching sequence" error. When I try to experiment with this or change anything, I get an object not set to reference error.

I sense that I've made a simple parsing mistake here, but any help would be appreciated (as well as where I've gone wrong and what I can do to prevent this in the future!)

Thank-you!

5
  • 1
    string name = xDoc.SelectSingleNode("//field[@name='name']").InnerText Commented May 1, 2016 at 9:13
  • Use Descendants("field") instead of Elements("field"). Commented May 1, 2016 at 9:18
  • @MathiasR.Jessen using LINQ is preferred, but if you must use XPath you need xDoc.XPathSelectElement(...). There is no SelectSingleNode method on XDocument. Commented May 1, 2016 at 9:26
  • @CharlesMager nice catch, was thinking about XmlDocument Commented May 1, 2016 at 9:29
  • Try this instead : var results = xDoc.Descendants("field").Where(x => x.Attribute("name").Value == "name").FirstOrDefault(); Commented May 1, 2016 at 10:18

1 Answer 1

2

The Elements query only finds immediate children of the current node. i.e. Elements will only return the root list element.

This either means you need to query like:

doc.Elements("list").Elements("resources").Elements(...

Or you can use Descendants, which will many any descendant of the current node, so:

var name = (string)doc.Descendants("field")
    .First(x => (string)x.Attribute("name") == "name");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank-you for the explanation, works perfectly now :).

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.