为什么XDocument.Parse抛出NotSupportedException?
问题描述:
我想解析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>";
一切正常,没有异常被抛出,所以我该怎么办错了吗?
答
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转换这个代码。我很快就写它只是用于测试目的
你是用xml解析器认真解析html的吗? – Kugel 2012-01-06 14:52:13
不,我不想用xml解析器解析html,再看看。 – marcin32 2012-01-06 15:15:52
XDocument.Load是一个xml解析器:) – Ku6opr 2012-01-06 15:22:46