2013-06-27 32 views
-3

大家好,我正在嘗試使用C#檢索Repeater中的XML數據。但它給我的錯誤 這裏是我的代碼xml數據不是retreiving

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>[email protected]</emailid> 
    <Comment>nice flower</Comment> 
    <CommentTime>6/22/2013 2:43:49 PM</CommentTime> 
    <status>Y</status> 
    </comments> 
    <comments> 
</tbcomments> 

這是給我的錯誤此 enter image description here

,請告訴我,我錯了?

回答

0

XML元素名稱是區分大小寫的前沒有簡化問題樣品就夠了。您的源XML中有CommentTime,但代碼中有Commenttime。我也建議使用字符串投下的.Value來避免NullReferenceException異常:

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(); 
+0

這樣一個小錯誤,我沒有發現我是多麼的愚蠢.. :(順便說一句感謝,現在的工作 –

0

當前問題:「Commenttime」拼錯了(應該是「CommentTime」)。

其他問題:

  • 非標準命名爲公共樣品中類成員。使用UpperCase作爲公共屬性/字段名稱。
  • 節點名稱不一致(大寫,小寫)。
  • 非DRY代碼:x.Element(someName).Value內聯重複幾次,因此laksking任何空檢查。
  • 發佈
相關問題