【问题标题】:Encoding ASCII as HTML将 ASCII 编码为 HTML
【发布时间】:2013-02-28 20:15:23
【问题描述】:

我正在尝试WebClient 中的DownloadData 方法。我目前的问题是我无法弄清楚如何将ASCII result<<\n>>)转换为>),它是由Encoding.ASCII.GetString(myDataBuffer); 生成的,从这个page.


(来源:iforce.co.nz

    /// <summary>
    /// Curl data from the PMID
    /// </summary>
    private void ClientPMID(int pmid)
    {
        //generate the URL for the client
        StringBuilder pmid_url_string = new StringBuilder();
        pmid_url_string.Append("http://www.ncbi.nlm.nih.gov/pubmed/").Append(pmid.ToString()).Append("?report=xml");
        Uri PMIDUri = new Uri(pmid_url_string.ToString());
        //declare and initialize the client
        WebClient client = new WebClient();
        // Download the Web resource and save it into a data buffer. 
        byte[] myDataBuffer = client.DownloadData(PMIDUri);
        this.DownloadCompleted(myDataBuffer);
    }
    /// <summary>
    /// Crawl over the binary from myDataBuffer
    /// </summary>
    /// <param name="myDataBuffer">Binary Buffer</param>
    private void DownloadCompleted(byte[] myDataBuffer)
    {
        string download = Encoding.ASCII.GetString(myDataBuffer);
        PMIDCrawler pmc = new PMIDCrawler(download, "/pre/PubmedArticle/MedlineCitation/Article");
        //iterate over each node in the file
        foreach (XmlNode xmlNode in pmc.crawl)
        {
            string AbstractTitle = xmlNode["ArticleTitle"].InnerText;
            string AbstractText = xmlNode["Abstract"]["AbstractText"].InnerText;
        }
    }

PMIDCrawler 的代码可在我关于DownloadStringCompletedEventHandler 的其他 SO 问题中找到。虽然string html = HttpUtility.HtmlDecode(nHtml); 的输出无效HTML (OR XML)(由于它没有响应xml http 标头),但在接收到来自Encoding.ASCII.GetString 的内容后。

【问题讨论】:

标签: c# html xml ascii webclient


【解决方案1】:

不幸的是,此服务器无法正确响应 Accept: text/xmlAccept: application/xml,因此您必须努力做到这一点 (HttpUtility)

string download = HttpUtility.HtmlDecode(Encoding.ASCII.GetString(myDataBuffer));

(或 .NET Fx 4.5+ 上的 WebUtility.Decode

string download = Encoding.ASCII.GetString(myDataBuffer);
if (download != null) { // this won't get all HTML escaped characters...
    download = download.Replace("&lt;", "<").Replace("&gt;", ">");
}

另请参阅this question 了解更多信息。

【讨论】:

  • +1 到目前为止是一个很好的建议,但无论如何要绕过每个attribute 被转义的事实?例如<?xml version=\"1.0\" encoding=\"utf-8\"?>
  • 确保你看到的 \"\n 不仅仅是 Visual Studio 调试器的工件,如果你在断点处检查一个字符串(这曾经让我一直)。如果我没记错 C#/.NET,您可以使用 Console.WriteLine 进行验证。
  • 你确定吗? curl --header "Accept:text/html" http://www.ncbi.nlm.nih.gov/pubmed/22918716\?report\=xml 向我展示了 HTML 实体转义了“XML”,但没有 \n 也没有 \" 令牌。
  • 我确实感觉 Encoding.ASCII 导致字符被转义,但我不是 100%。
  • 你说得对,它一定是神器。我在调试期间检查的时间不对。
猜你喜欢
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 2012-06-20
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
相关资源
最近更新 更多