2011-03-21 90 views
2

XML条件linqToXml

<Questions> 
    <Question> 
     <Id>1</Id> 
     <Text>aaa</Text> 
    </Question> 
    <Question> 
     <Id>2</Id> 
     <Text>bbb</Text> 
    </Question> 
</Questions> 

代码

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, 
         }; 

此代码elements.count()==> 0

我想从XML选择其中txt=='aaa'

回答

1

let txt = element.Element("Text")返回一个XElement而不是文本,所以你的CompareTo cond ition将爆炸而不是检查文本值。

相反,您可以通过.Value属性获取节点的值。

... 
let txt = element.Element("Text").Value 
... 

线var elements = from element in doc.Descendants("Question")将成功查找的元素,但作为一种实践,你可能想从根节点或相对层次去。

... 
var elements = from element in doc.Root.Descendants("Question") 
... 

代码的其余部分看起来很好(更少的异常处理)。

以下为我工作...

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