开发者

condition in linqToXml

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'


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜