大家好我正试图用C#检索转发器中的XML数据。但它给了我错误 这是我的代码
var doc = XDocument.Load(Server.MapPath("~/Data/comments.xml"));
var result = doc.Descendants("comments").Where(x => x.Element("postid").Value == Request.QueryString["id"] && x.Element("status").Value == "Y").Select(x => new
{
id=x.Element("id").Value,
name = x.Element("name").Value,
comment = x.Element("Comment").Value,
commenttime = x.Element("Commenttime").Value
//status=x.Element("status").Value
}).OrderByDescending(x => x.id).Take(1);
Repeater2.DataSource = result;
Repeater2.DataBind();
}
这是我的xml
<?xml version="1.0" encoding="utf-8"?>
<tbcomments>
<comments>
<id>1</id>
<postid>4</postid>
<name>azad</name>
<emailid>chouhan.azad99@gmail.com</emailid>
<Comment>nice flower</Comment>
<CommentTime>6/22/2013 2:43:49 PM</CommentTime>
<status>Y</status>
</comments>
<comments>
</tbcomments>
这给了我错误
请告诉我我哪里错了?答案 0 :(得分:0)
当前问题:“评论时间”拼写错误(应为“评论时间”)。
其他问题:
x.Element(someName).Value
内联重复多次,因此会进行任何空检查。答案 1 :(得分:0)
XML元素名称区分大小写。您的源XML中有CommentTime,但代码中有Commenttime。我还建议使用字符串强制转换而不是.Value
来避免NullReferenceExceptions:
var doc = XDocument.Load(Server.MapPath("~/Data/comments.xml"));
var result = doc.Descendants("comments")
.Where(x => x.Element("postid").Value ==
Request.QueryString["id"] &&
x.Element("status").Value == "Y")
.Select(x => new
{
id= (string)x.Element("id"),
name = (string)x.Element("name"),
comment = (string)x.Element("Comment"),
commenttime = (string)x.Element("CommentTime")
//status=x.Element("status").Value
}).OrderByDescending(x => x.id).Take(1);
Repeater2.DataSource = result;
Repeater2.DataBind();