XML.Linq get value based on another value

I am trying to user Linq to XML to pull out a value from some xml based on another value..

Here is my xml

<Lead>
<ID>1189226</ID>
<Client>
    <ID>8445254</ID>
    <Name>City of Lincoln Council</Name>
</Client>
<Contact>
    <ID>5747449</ID>
    <Name>Fred Bloggs</Name>
</Contact>
<Owner>
    <ID>36612</ID>
    <Name>Joe Bloggs</Name>
</Owner>
<CustomFields>
    <CustomField>
      <ID>31961</ID>
      <Name>Scotsm_A_n_Authority_Good</Name>
      <Boolean>true</Boolean>
    </CustomField>
    <CustomField>
      <ID>31963</ID>
      <Name>Scotsma_N_Need Not Want</Name>
      <Boolean>false</Boolean>
    </CustomField>
 </CustomFields>

So, for example, I want to try and get the value of <Boolean> in the <CustomField> where <Name> equals "Scotsm_A_n_Authority_Good" which should be "true"

I have tried the following:

var xmlAnswers = xe.Element("CustomFields").Element("CustomField").Element("Scotsm_A_n_Authority_Good");

But I get an error saying that:

The ' ' character, hexadecimal value 0x20, cannot be included in a name...

Can anyone help please?

Jon Skeet
people
quotationmark

You're looking for the wrong thing at the moment. You should be looking for a CustomField element with a Name element with the specified value:

string target = "Scotsm_A_n_Authority_Good"; // Or whatever
var xmlAnswers = xe.Element("CustomFields")
                   .Elements("CustomField")
                   .Where(cf => (string) cf.Element("Name") == target);

This will give you all the matching CustomField elements. You can then get the Boolean value with something like:

foreach (var answer in xmlAnswers)
{
    int id = (int) answer.Element("ID");
    bool value = (bool) answer.Element("Boolean");
    // Use them...
}

(You could extract the ID and value in the LINQ query of course...)

people

See more on this question at Stackoverflow