系统.Xml.XmlException - 缺少根元素。

9
我正在制作一个Web应用程序,该应用程序从网站获取RSS源(URL存储在数据库中),然后将它们加载到我的Web应用程序中。但是我遇到了以下错误:

System.Xml.XmlException: 根元素丢失。第2行,第2个位置处有多个根元素。在此行:rssdoc.load(rssStream)。

异常详细信息:System.Xml.XmlException: 根元素丢失。第2行,第2个位置处有多个根元素。如何使用单个XML元素封装其他所有内容?

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Net;
using System.Text;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public partial class poletics : System.Web.UI.Page
{
    public SqlConnection oldbcon = new SqlConnection();
    static int n = 0;
    static DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        oldbcon = opncon();

        using (oldbcon)
        {
            SqlDataAdapter ad = new SqlDataAdapter("SELECT * from LebPolRss", oldbcon);
            ad.Fill(dt);
        }
        int f = 3;
        while (n < f)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                Literal feed = new Literal();
                try
                {
                    feed.Text = ProcessRss(dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString());
                }
                catch (WebException ex)
                {
                    WebResponse response = ex.Response;
                }
                Panel1.Controls.Add(feed);
            }
            n++;
        }
    }
    public static string ProcessRss(string rssUrl, string feed)
    {
        WebRequest request = WebRequest.Create(rssUrl);
        WebResponse response = request.GetResponse();
        StringBuilder sb = new StringBuilder("");
        Stream rssStream = response.GetResponseStream();
        XmlDocument rssDoc = new XmlDocument();

        rssDoc.Load(rssStream);//here is the line where the exception thrown
        XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item");

        string title = "";
        string link = "";
        string description = "";
        int upperlimit = rssItems.Count;
        if (upperlimit > n)
            upperlimit = n + 1;
        if (upperlimit > 0)
        {
            sb.Append("<ul>");
            for (int i = 0; i < upperlimit - n; i++)
            {
                XmlNode rssDetail;
                rssDetail = rssItems.Item(i + n).SelectSingleNode("title");
                if (rssDetail != null)
                {
                    if (feed.ToString().Equals("tayyar"))
                    {
                        title = rssDetail.InnerText.Substring(5);
                    }
                    else
                    {
                        if (rssDetail.InnerText.Length > 75)
                        {
                            title = rssDetail.InnerText.Substring(0, 75);
                        }
                        else
                        {
                            title = rssDetail.InnerText;
                        }
                    }
                }
                else
                {
                    title = "";
                }

                rssDetail = rssItems.Item(i + n).SelectSingleNode("link");
                if (rssDetail != null)
                {
                    if (feed.ToString().Equals("tayyar"))
                    {
                        if (rssDetail.InnerText.Substring(0, 21).CompareTo("http://www.tayyar.org") != 0)
                        {
                            link = "http://www.tayyar.org" + rssDetail.InnerText;
                        }
                        else
                        {
                            link = rssDetail.InnerText;
                        }
                    }
                    else
                    {
                        link = rssDetail.InnerText;
                    }
                }
                else
                {
                    link = "";
                }
                rssDetail = rssItems.Item(i + n).SelectSingleNode("description");
                if (rssDetail != null)
                {
                    if (!rssDetail.InnerText.Substring(3, 3).Equals("Ad:"))
                    {

                        description = rssDetail.InnerText;
                    }

                }
                else
                {
                    description = "";
                }
                switch (feed)
                {
                    case "tayyar": sb.Append("<div class='imgsep'><li><img src='logos/tayyar.jpg' width='50px' height='30px'/>&nbsp;&nbsp;&nbsp;<a href='" + link + "' target='_blank'>" + title + "</a>&nbsp;<img src='Images/smallarrow.png'/></li></div>");
                        break;
                    case "14march": sb.Append("<div class='imgsep'><li><img src='logos/14march.jpg' width='50px' height='30px'/>&nbsp;&nbsp;&nbsp;<a href='" + link + "' target='_blank'>" + title + "</a>&nbsp;<img src='Images/smallarrow.png'/></li></div>");
                        break;
                    case "annahar": sb.Append("<div class='imgsep'><li><img src='logos/annahar.jpg' width='50px' height='30px'/>&nbsp;&nbsp;&nbsp;<a href='" + link + "' target='_blank'>" + title + "</a>&nbsp;<img src='Images/smallarrow.png'/></li></div>");
                        break;
                    case "alakhbar": sb.Append("<div class='imgsep'><li><img src='logos/akhbar.jpg' width='50px' height='30px'/>&nbsp;&nbsp;&nbsp;<a href='" + link + "' target='_blank'>" + title + "</a>&nbsp;<img src='Images/smallarrow.png'/></li></div>");
                        break;
                    case "sadabeirut": sb.Append("<div class='imgsep'><li><img src='logos/echobeirut.png' width='50px' height='30px'/>&nbsp;&nbsp;&nbsp;<a href='" + link + "' target='_blank'>" + title + "</a>&nbsp;<img src='Images/smallarrow.png'/></li></div>");
                        break;
                    case "assafir": sb.Append("<div class='imgsep'><li><img src='logos/assafir.png' width='50px' height='30px'/>&nbsp;&nbsp;&nbsp;<a href='" + link + "' target='_blank'>" + title + "</a>&nbsp;<img src='Images/smallarrow.png'/></li></div>");
                        break;
                    case "aliwaa": sb.Append("<div class='imgsep'><li><img src='logos/aliwaa.jpg' width='50px' height='30px'/>&nbsp;&nbsp;&nbsp;<a href='" + link + "' target='_blank'>" + title + "</a>&nbsp;<img src='Images/smallarrow.png'/></li></div>");
                        break;
                }
            }
            sb.Append("</ul>");
        }
        return sb.ToString();
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        oldbcon = opncon();
        using (oldbcon)
        {
            SqlDataAdapter ad = new SqlDataAdapter("SELECT * from LebPolRss", oldbcon);
            ad.Fill(dt);
        }
        n = 4;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            Literal feed = new Literal();
            try
            {
                feed.Text = ProcessRss(dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString());
            }
            catch (WebException ex) { WebResponse response = ex.Response; }
            Panel1.Controls.Add(feed);
        }
        LinkButton1.Visible = false;
    }
    public static SqlConnection opncon()
    {
        string connectionString = "Data Source=RAYYAN-THINK;Initial Catalog=newsProject;Integrated Security=True";
        SqlConnection conn = new SqlConnection(connectionString);
        return conn;
    }
}

堆栈跟踪:

[XmlException: Root element is missing.]
   System.Xml.XmlTextReaderImpl.Throw(Exception e) +69
   System.Xml.XmlTextReaderImpl.ParseDocumentContent() +5589128
   System.Xml.XmlTextReaderImpl.Read() +215
   System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) +145
   System.Xml.XmlDocument.Load(XmlReader reader) +107
   System.Xml.XmlDocument.Load(Stream inStream) +130
   poletics.ProcessRss(String rssUrl, String feed) in c:\Users\RAYYAN\Documents\Visual Studio 2012\WebSites\WebSite1\poletics.aspx.cs:57
   poletics.Page_Load(Object sender, EventArgs e) in c:\Users\RAYYAN\Documents\Visual Studio 2012\WebSites\WebSite1\poletics.aspx.cs:36
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

1
http://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title - Soner Gönül
显然,这似乎是与xml文件有关的问题。也许你可以发布引发此异常的xml文件? - user1567896
这是太多的代码了。你应该运用自己的判断力,仅发布相关部分,如果可能,请发布XML,并清楚地说明异常抛出的行数。 - H H
抱歉忘记了异常抛出的代码行:rssdoc.load(rssStream); 我想补充说明并不总是会出现这个错误。我该如何提供所有从中获取源的URL的XML文件!!! - ra22
1个回答

6

错误解释了异常的最常见情况:您的xml中缺少根元素。

这意味着,您很可能有多个“根”元素,因此它们不是根元素。您需要一个单独的xml元素来封装其他所有内容。这是需要检查的第一件事。


2
也许你可以添加一个小例子来说明它。 - Daniel Abou Chleih
好吧,这不是我的XML...它是他们的XML,为什么有时候它完美运行,有时候会抛出异常?除了如何处理此异常之外,我还可以如何将所有内容封装在单个XML元素中?请给出一个例子。感谢您的帮助。 - ra22
使用try-catch来处理异常。在开始调整自己的软件之前,最好先修复问题的源头。检查为什么有时会得到正确的XML,有时候不会。你不应该将XML包围起来,它应该以这种方式交付。 - Daniel Abou Chleih
Daniel Abou Chleih,请帮我,告诉我该怎么做,非常感谢您的回复。 - ra22
“shouldn't surround the XML” 是什么意思? - ra22
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接