linqToXml 中的条件
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()==>0
我希望从 xml 中进行选择,其中 txt=='aaa'
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
let txt = element.Element("Text")
行返回 XElement 而不是文本,因此您的CompareTo
条件将失效,而不是检查文本值。相反,您可以通过
.Value
属性获取节点的值。var elements = from element in doc.Descendants("Question") 行将成功查找元素,但作为实践,您可能希望从根节点或相对层次结构查找。
代码的其余部分看起来很好(较少的异常处理)。
以下内容对我有用......
The line
let txt = element.Element("Text")
returns a XElement instead of the text so yourCompareTo
condition will blow up instead of checking the text values.Instead you can get the value of the node via the
.Value
property.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.The rest of the code seems fine (less exception handling).
The following worked for me...