c# - 为什么 XDocument.Parse 抛出 NotSupportedException?

标签 c# silverlight windows-phone-7 linq-to-xml

我正在尝试使用 XDocument.Parse 解析 xml 数据,这会抛出 NotSupportedException,就像在主题中一样:Is XDocument.Parse different in Windows Phone 7?我根据发布的建议更新了我的代码,但它仍然无济于事。前段时间我使用类似(但更简单)的方法解析 RSS,并且效果很好。

public void sList()
        {

            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            string url = "http://eztv.it";
            Uri u = new Uri(url);
            client.DownloadStringAsync(u);
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);


        }

    private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        try
        {
            string s = e.Result;
            s = cut(s);

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.DtdProcessing = DtdProcessing.Ignore;


            XDocument document = null;// XDocument.Parse(s);//Load(s);
            using (XmlReader reader = XmlReader.Create(new StringReader(e.Result), settings))
            {
                document = XDocument.Load(reader); // error thrown here
            }

            // ... rest of code
        }
        catch (Exception ex)
        {
            MessageBox.Show( ex.Message);
        }

    }

    string cut(string s)
    {
        int iod = s.IndexOf("<select name=\"SearchString\">");
        int ido = s.LastIndexOf("</select>");

        s = s.Substring(iod, ido - iod + 9);

        return s;
    }

当我用字符串 s 代替

//string s = "<select name=\"SearchString\"><option value=\"308\">10 Things I Hate About You</option><option value=\"539\">2 Broke Girls</option></select>";

一切正常,没有抛出异常,那么我做错了什么?

最佳答案

e.Result中有'&'等特殊符号。

我只是尝试用 HttpUtility.HtmlEncode() 替换这些符号(除 '<'、'>'、'"' 之外的所有符号),并且 XDocument 解析了它

更新:

我不想展示我的代码,但你没有给我机会:)

 string y = "";
 for (int i = 0; i < s.Length; i++)
 {
      if (s[i] == '<' || s[i] == '>' || s[i] == '"')
      {
           y += s[i];
      }
      else
      {
           y += HttpUtility.HtmlEncode(s[i].ToString());
      }
 }
 XDocument document = XDocument.Parse(y);
 var options = (from option in document.Descendants("option")
      select option.Value).ToList();

它在 WP7 上对我有用。 请不要将此代码用于 html 转换。我很快就写了它只是为了测试目的

关于c# - 为什么 XDocument.Parse 抛出 NotSupportedException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8759515/

相关文章:

c# - WP7 上 ListPicker 的 caliburn.micro 绑定(bind)约定

c# - FtpWebResponse IDisposable 是否关闭响应?

c# - 在 ActionLink 的 RouteValues 中传递 IEnumerable 属性

silverlight - 如何使用控件或类/函数将 TIFF 转换为 JPG Inside Silverlight,客户端?

silverlight - WP7 MediaElement 下载问题

windows-phone-7 - 更改系统托盘进度指示器颜色

c# - 如何将 json 字符串反序列化为域对象?

c# - 释放鼠标时组合框意外自动关闭

c# - 如何在 C# 中正确切换枚举?

c# - 使用 Caliburn.Micro 的分层导航模型