c#中的LINQ to XML查询

时间:2009-09-29 09:58:55

标签: xml linq

如何查询下面的文档,这样它会给我“id”的值(状态后根目录中的那个)?

这会产生错误(对象引用未设置为对象的实例。)

            using (WebResponse response = request.GetResponse())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string responseString = reader.ReadToEnd();
                XDocument document = XDocument.Parse(responseString, LoadOptions.None);
                return (from e in document.Root.Elements("status")
                        select e.Element("id").Element("name").Value).SingleOrDefault().ToString();
                return responseString;
            }
        }

XML

<?xml version="1.0" encoding="UTF-8"?>
<status>
  <created_at>Tue Sep 29 09:33:23 +0000 2009</created_at>
  <id>xxxxxxxxxxxxxx</id>
  <text>test</text>
  <source><a href="http://apiwiki.twitter.com/" rel="nofollow"&gt;API</a&gt;</source>
  <truncated>false</truncated>
  <in_reply_to_status_id></in_reply_to_status_id>
  <in_reply_to_user_id></in_reply_to_user_id>
  <favorited>false</favorited>
  <in_reply_to_screen_name></in_reply_to_screen_name>
  <user>
    <id>xxxx</id>
    <name>xxx</name>
    <screen_name>xxx</screen_name>
   </user>
</status>

1 个答案:

答案 0 :(得分:1)

您的根元素已经是“状态”。因此以下代码:

return (from e in document.Root.Elements("status")
                        select e.Element("id").Element("name").Value).SingleOrDefault().ToString();

需要阅读:

return document.Root.Element("id").Value;