【问题标题】:XDocument says Data at the root level is invalid?XDocument 说根级别的数据无效?
【发布时间】:2013-08-22 13:31:00
【问题描述】:

我正在尝试解析一个 XML,它位于 url:

try
{
    var xDoc = XDocument.Parse(requestedURL);
    Response.Write("asd: " + xDoc.Descendants("entry").Count());
}
catch (Exception err)
{
    Response.Write(err.Message);
}

但它回复Data at the root level is invalid. Line 1, position 1.

我哪里错了?

【问题讨论】:

    标签: c# .net xml linq-to-xml deserialization


    【解决方案1】:

    您应该使用XDocument.Load 而不是XDocument.Parse。那是因为XDocument.Parse 期望接收 XML 字符串,而您正试图从 URL 加载它。

    编辑

    XML 命名空间也有问题。试试这个

    var xDoc = XDocument.Load(requestedURL);
    XNamespace ns = "http://www.w3.org/2005/Atom";
    var count = xDoc.Descendants(ns + "entry").Count();
    

    http://msdn.microsoft.com/en-us/library/bb343181.aspx

    【讨论】:

    • 已经这样做了,但是xDoc.Descendants("entry").Count() 说的是 0,这不是 0。所以我猜 load 不解析 XML?
    • @markzzz 向 xml 提供者询问。它使用 xmlns="http://www.w3.org/2005/Atom" 作为默认命名空间。
    • 我的意思是:为什么我需要在 XDocument 中使用命名空间!该字段称为entry,而不是http://www.w3.org/2005/Atom entry
    • @markzzz 我认为您对语法感到困惑。这个和上面var entry = XName.Get("entry", "http://www.w3.org/2005/Atom"); var count = xDoc.Descendants(entry).Count();一样
    【解决方案2】:

    试试这个。

    try
    {
      var xDoc = XDocument.Load(requestedURL);
      Response.Write("asd: " + xDoc.Descendants("entry").Count());
    }
    catch (Exception err)
    {
      Response.Write(err.Message);
    } 
    

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 2014-01-17
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 2011-05-22
      相关资源
      最近更新 更多