XmlDocument.LoadXml()抛出ComException类型的异常

时间:2011-11-30 17:57:04

标签: c# .net xml windows-runtime

我正在尝试解析从this link返回的xml文档,但我得到类型ComException的例外,其中包含以下消息:

Error HRESULT E_FAIL has been returned from a call to a COM component.

以下是代码:

        try
        {
            //...
            string EPGXML = await DownloadAsync(url);

            var xmldoc = new XmlDocument();
            xmldoc.LoadXml(EPGXML); //this line throws the exception
            //...rest of the code
        }
        catch (Exception)
        {
            //I get here...
        }

你能帮我解释为什么我收到这条消息,我该如何解决这个问题?感谢。

修改

我正在使用这个函数读取XML的来源(也许我在这里错了,我应该做一些事情来获取UTF-8中的字符串,因为我在调试中看不到字符串中的德语字符模式(观察窗口):

    private async static Task<string> DownloadPageAsync(string url)
    {
        try
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.UseDefaultCredentials = true;
            handler.AllowAutoRedirect = true;
            handler.UseCookies = true;
            HttpClient client = new HttpClient(handler);
            client.MaxResponseContentBufferSize = 10000000;
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();

            string responseBody = response.Content.ReadAsString();
            return responseBody;
        }
        catch (Exception ex)
        {
            return "error" + ex.Message;
        }
    }

2 个答案:

答案 0 :(得分:7)

您提供的XML无效,至少Firefox的说法是这样的:

  

Erreur d'analysis XML:malformé   进驻:http://www.onlinetvrecorder.com/?aktion=epg_export&format=xml&btn_ok=OK&&gt;台= 3SAT,ANIXE,ARD&amp; from = 30.11.2011&amp; to = 30.11.2011   Numérodeligne 218,Colonne 193:

(对不起法国人)

仔细观察,看起来解析器在“ö”字符上打破了“Plötzlich”这个词。

您应该使用CDATA来防止这种情况:

<![CDATA[Your text here can contain special chars]]>

答案 1 :(得分:3)

不要尝试使用html页面加载XML文档。使用Html Agility Pack本来就是这样做的。

编辑:如果你只想把网页的来源作为一个字符串,这应该可以解决问题。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com/posts/8331002");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string data = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
    data = reader.ReadToEnd();

Console.WriteLine(data);