2012-07-30 134 views
0

我尝试解析XML文件时遇到问题,因为Read()方法似乎在跳过一些行。首先,这里是XML文件:阅读方法跳过节点

<comments> 
    <comment id="e2d6d918-0fbb-4434-9e43-6b028b872867" parentid="00000000-0000-0000-0000-000000000000" approved="True" spam="False" deleted="False"> 
     <date>2012-06-14 18:40:55</date> 
     <author>*content here*</author> 
     <email>*content here*</email> 
     <country>*content here*</country> 
     <ip>*content here*</ip> 
     <moderatedby>*content here*</moderatedby> 
     <content>*content here*</content> 
    </comment> 
    <comment id="7f74b8af-73e5-407f-abcb-c3cba5ffc611" parentid="e2d6d918-0fbb-4434-9e43-6b028b872867" approved="True" spam="False" deleted="False"> 
     <date>2012-06-15 01:59:34</date> 
     <author>*content here*</author> 
     <email>*content here*</email> 
     <country>*content here*</country> 
     <ip>*content here*</ip> 
     <website>*content here*</website> 
     <content>*content here*</content> 
    </comment> 
    </comments> 

而且到代码:

(我使用的是XmlTextReader

  while (reader.Read()) 
      { 
       if (reader.Name == "comment" && reader.NodeType == XmlNodeType.Element) 
       { 
        Comment newComment = new Comment(); 

        newComment.PostId = postId; 

        reader.MoveToAttribute("deleted"); 
        newComment.IsDeleted = Convert.ToBoolean(reader.Value); 
        reader.MoveToAttribute("spam"); 
        newComment.IsSpam = Convert.ToBoolean(reader.Value); 
        reader.MoveToAttribute("approved"); 
        newComment.IsApproved = Convert.ToBoolean(reader.Value); 
        reader.MoveToAttribute("parentid"); 
        newComment.ParentCommentId = new Guid(reader.Value); 
        reader.MoveToAttribute("id"); 
        newComment.PostCommentId = new Guid(reader.Value); 

        reader.ReadToFollowing("date"); 
        newComment.CommentDate = Convert.ToDateTime(reader.ReadString()); 

        reader.ReadToFollowing("author"); 
        newComment.Author = reader.ReadString(); 

        reader.ReadToFollowing("email"); 
        newComment.Email = reader.ReadString(); 

        reader.ReadToFollowing("country"); 
        newComment.Country = reader.ReadString(); 

        reader.ReadToFollowing("ip"); 
        newComment.Ip = reader.ReadString(); 

        reader.ReadToFollowing("website"); 
        newComment.Website = reader.ReadString(); 

        //reader.ReadToFollowing("moderatedBy"); 
        newComment.ModeratedBy = string.Empty; 

        //reader.ReadToFollowing("avatar"); 
        newComment.Avatar = string.Empty; 

        reader.ReadToFollowing("content"); 
        newComment.CommentContent = reader.ReadString(); 

        comments.Add(newComment); 
       } 
      } 

编辑:我做了一些更多的调试,发现我试图阅读不存在的网站元素。

+0

会做人,抱歉。 – TheGateKeeper 2012-07-30 20:29:47

回答

0

问题是我试图读取所有评论节点不存在的“网站”元素。这导致读者继续搜索,直到它找到一个为止(就像它在上面显示的XML文件中通过转到第二个评论中那样)或者到达文件的末尾。

我删除了该检查,现在它可以工作。