如何从包含& ndash字符的xml REST服务响应加载XmlDocument

时间:2014-01-24 15:50:16

标签: c# xml

我收到了一个xml响应,其中一个元素包含 &ndash 字符。这样可以防止字符串加载到XmlDocument。我尝试了很多事情但没有成功。有关如何妥善解决此问题的任何建议?

我正在使用c#从控制台应用程序发出请求。

    static void Test1()
    {

        //for testing only
        string url = Properties.Settings.Default.GCAPIUrl + "?since=2013-12-01";
        //string url = Properties.Settings.Default.GCAPIUrl + "?survey_instance_id=745408";

        //uncomment this prior to going live
        //string url = Properties.Settings.Default.GCAPIUrl + "?since=" + DateTime.Today.Date.ToString("yyyy-MM-dd");
        //the following will retrieve responses for the last two days
        //string url = Properties.Settings.Default.GCAPIUrl + "?days=2";

        HttpWebRequest myReq = WebRequest.Create(url) as HttpWebRequest;

        myReq.ContentType = "application/xml";

        string username = Properties.Settings.Default.APIUserName;
        string password = Properties.Settings.Default.APIPassword;

        string usernamePassword = username + ":" + password;
        CredentialCache mycache = new CredentialCache();
        mycache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
        myReq.Credentials = mycache;
        myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

        HttpWebResponse wr = myReq.GetResponse() as HttpWebResponse;

        Stream receiveStream = wr.GetResponseStream();
        StreamReader responseReader = new StreamReader(receiveStream);
        string strResponse = responseReader.ReadToEnd();

        string strResponseXML = RemoveInvalidXmlChars(strResponse.ToString());
        XmlDocument xdoc = new XmlDocument();
        xdoc.LoadXml(strResponseXML);

        wr.Close();
    }

    static string RemoveInvalidXmlChars(string strXMLString)
    {
        strXMLString = strXMLString.Replace("—", "-");
        strXMLString = strXMLString.Replace("–", "-");
        return strXMLString;
    }

0 个答案:

没有答案