【发布时间】:2015-05-12 23:50:53
【问题描述】:
我需要从 Web 读取一个编码为 ISO-8859-1 的 XML 文件。用它创建一个 XmlDocument 后,我尝试将它的一些 InnerText 转换为 UTF。但这没有用。然后我尝试更改 HttpClient 上的编码。响应字符串的格式正确,但在创建 XmlDocument 时,应用程序崩溃并出现异常:HRESULT: 0xC00CE55F 或 XML 字符串上出现非预期字符。我该如何解决这个问题?
代码片段:
private static async Task<string> GetResultsAsync(string uri)
{
var client = new HttpClient();
var response = await client.GetByteArrayAsync(uri);
var responseString = Encoding.GetEncoding("iso-8859-1").GetString(response, 0, response.Length - 1);
return responseString;
}
public static async Task GetPodcasts(string url)
{
var progrmas = await GetGroupAsync("prog");
HttpClient client = new HttpClient();
//Task<string> pedido = client.GetStringAsync(url);
//string res = await pedido; //Gets the string with the wrong chars, LoadXml doesn't fails
res = await GetResultsAsync(url); //Gets the string properly formatted
XmlDocument doc = new XmlDocument();
doc.LoadXml(res); //Crashes here
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//item");
//Title
var node_titles = root.SelectNodes("//item/title");
IEnumerable<string> query_titles = from nodess in node_titles select nodess.InnerText;
List<string> list_titles = query_titles.ToList();
//........
for (int i = 0; i < list_titles.Count; i++)
{
PodcastItem podcast = new PodcastItem();
string title = list_titles[i];
//First attempt to convert a field from the XmlDocument, with the wrong chars. Only replaces the bad encoding with a '?':
//Encoding iso = Encoding.GetEncoding("ISO-8859-1");
//Encoding utf8 = Encoding.UTF8;
//byte[] utfBytes = utf8.GetBytes(title);
//byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
//string msg = iso.GetString(isoBytes, 0, isoBytes.Length - 1);
PodcastItem dataItem = new PodcastItem(title + pubdate, title, link, description, "", pubdate);
progrmas.Items.Add(dataItem);
}
}
【问题讨论】:
-
什么是
title?真的不清楚你想做什么。还要注意XmlDocument和XDocument是不同的类。如果您已经将文档转换为string,可能为时已晚 - 您应该将其以原始 binary 表示形式(例如作为流)提供,并让 XML 解析器处理解码。 -
我已经更正了你提到的问题。
-
您是否尝试过将二进制数据提供给 XmlDocument? XML 文件 advertise 是否采用 ISO-8859-1 编码? (该文档是否可以公开访问,以便我们自己寻找?)一个简短但完整的程序来证明这个问题真的很有帮助。
-
当前代码与文档的 url:pastebin.com/sPbxTShC
-
这不是一个简短但完整的程序,您应该将其包含在问题中。
标签: c# xml web-services encoding