Check if the node exist in XDocument

I have this xml:

<Rejectedparameters>
  <parameter>
    <name>CO</name>
    <value>5.34</value>
  </parameter>
  <parameter>
    <name>CO2</name>
    <value>10.1</value>
  </parameter>
  <parameter>
    <name>HC</name>
    <value>473</value>
  </parameter>
  <parameter>
    <name>O2</name>
    <value>2</value>
  </parameter>
</Rejectedparameters>

I need to check if for example a node exists - like this :

  int Gvalue = (from x in document.Elements("Rejectedparameters").Elements("parameter")
                from p in x.Elements("Name")
                where x.Element("CO").Value.ToString() != string.Empty
                select x).Count();

but the Gvalue is 0 - why? As you can see, the CO is exists in the XML.

Jon Skeet
people
quotationmark

Firstly, each parameter element only has a single name, so just use Element for that.

Next, use name as the element you're looking for, not Name.

Finally, you're looking for a value of CO, not an element called CO. So you'd have something like:

var query = doc
    .Root
    .Elements("parameter")
    .Where(parameter => (string) parameter.Element("name") == "CO" &&
                        !string.IsNullOrEmpty((string) parameter.Element("value"));
var count = query.Count(); // It's not clear why this was Gvalue in your original code

I've guessed at what you were trying to do with the check for an empty string... you may not need the second part of the filter. I've assumed that you don't only want to get the count - that you actually want to use the elements too.

An alternative approach would be to convert all the parameters with a query first:

var parameters = doc.Root.Elements("parameter").Select(p =>
    new { Name = (string) p.Element("name"), Value = (string) p.Element("value") });
// Just as an example...
var co = parameters.SingleOrDefault(p => p.Name == "CO");

people

See more on this question at Stackoverflow