linqToXml中的条件

时间:2011-03-21 17:08:23

标签: xml linq xml-serialization linq-to-xml linq-to-objects

XML

<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()==&gt; 0

我希望从xml中选择txt=='aaa'

1 个答案:

答案 0 :(得分:1)

let txt = element.Element("Text")行会返回一个XElement而不是文本,因此您的CompareTo条件会爆炸而不是检查文本值。

相反,您可以通过.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