2012-01-06 96 views
4

我想解析XML數據使用XDocument.Parse wchich拋出NotSupportedException,就像在主題:Is XDocument.Parse different in Windows Phone 7?和我更新我的代碼根據張貼的建議,但它仍然沒有幫助。前段時間我使用類似(但更簡單)的方法解析RSS,並且工作得很好。爲什麼XDocument.Parse拋出NotSupportedException?

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>"; 

一切正常,沒有異常被拋出,所以我該怎麼辦錯了嗎?

+2

你是用xml解析器認真解析html的嗎? – Kugel 2012-01-06 14:52:13

+0

不,我不想用xml解析器解析html,再看看。 – marcin32 2012-01-06 15:15:52

+0

XDocument.Load是一個xml解析器:) – Ku6opr 2012-01-06 15:22:46

回答

6

e.Result中有特殊符號,如'&'。

我只是想取代這個符號(除了 '<', '>', ''「)與HttpUtility.HtmlEncode()XDocument解析它

UPD:

我並不想表明我的代碼,但你給我留下任何機會:)

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轉換這個代碼。我很快就寫它只是用於測試目的

+0

不,這沒有幫助,它仍然拋出NotSupportedException。也許你在普通的C#應用​​程序中試過這段代碼,它在非-WP7應用程序中工作得很好。 – marcin32 2012-01-06 15:28:01

+0

看到我的更新... – Ku6opr 2012-01-06 15:34:53

+0

哦,我沒有注意到那些角色在那裏,我只是假定他們不會使用它們。感謝您的幫助和寬容。 – marcin32 2012-01-06 15:48:16

相關問題