Reputation: 5297
XML
<Questions>
<Question>
<Id>1</Id>
<Text>aaa</Text>
</Question>
<Question>
<Id>2</Id>
<Text>bbb</Text>
</Question>
</Questions>
Code
question="aaa";
var doc = XDocument.Load(Server.MapPath(".") + "\\Questions.xml");
var elements = from element in doc.Descendants("Question")
let txt = element.Element("Text")
where question.CompareTo (txt)==0
select new
{
Id = element.Element("Id").Value,
};
This code elements.count()==>0
I would Like that select from xml where txt=='aaa'
Upvotes: 2
Views: 60
Reputation: 82335
The line let txt = element.Element("Text")
returns a XElement instead of the text so your CompareTo
condition will blow up instead of checking the text values.
Instead you can get the value of the node via the .Value
property.
...
let txt = element.Element("Text").Value
...
The line var elements = from element in doc.Descendants("Question")
will successfully lookup the elements but as a practice you might want to go from the root node or relative hierarchy.
...
var elements = from element in doc.Root.Descendants("Question")
...
The rest of the code seems fine (less exception handling).
The following worked for me...
string xml = @"<Questions>
<Question>
<Id>1</Id>
<Text>aaa</Text>
</Question>
<Question>
<Id>2</Id>
<Text>bbb</Text>
</Question>
</Questions>";
string question = @"aaa";
var doc = XDocument.Parse(xml);
var elements = from element in doc.Root.Descendants("Question")
let txt = element.Element("Text").Value
where question.CompareTo(txt)==0
select new
{
Id = element.Element("Id").Value,
};
Console.WriteLine(elements.Count()); //1
Upvotes: 1