将字符串转换为 xml 时的 .net 无效字符

.net invalid characters when converting string to xml

我正在尝试将网络响应转换为 xml。但是,即使 xml 字符串得到验证,当我尝试将响应字符串转换为 XmlDocument 时,我也会得到 "invalid character error"。我还在 here 中应用了已接受的答案。代码如下:

public XmlDocument RequestAndResponseHelper(string requestStr, string directory)
{
    var request = (HttpWebRequest)WebRequest.Create(directory);

    var data = Encoding.ASCII.GetBytes(requestStr);
    request.Method = "POST";
    request.ContentType = "text/xml";
    request.ContentLength = data.Length;
    using (var stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }
    var response = (HttpWebResponse)request.GetResponse();
    string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

    //Accepted answer applied
    StringBuilder newString = new StringBuilder();
    char ch;

    for (int i = 0; i < responseString.Length; i++)
    {

        ch = responseString[i];
        // remove any characters outside the valid UTF-8 range as well as all control characters
        // except tabs and new lines
        //if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r')
        //if using .NET version prior to 4, use above logic
        if (XmlConvert.IsXmlChar(ch)) //this method is new in .NET 4
        {
            newString.Append(ch);
        }
    }
    String newStr = newString.ToString();

    XmlDocument rs = new XmlDocument();
    rs.Load(newStr);

    return rs;
}

在这两种情况下(应用链接答案中的代码或不应用),Xml 字符串均有效且相同。

你能推荐任何其他解决方案吗?

您正在使用 XmlDocument.Load, which is meant to accept a URL. I believe you meant to use XmlDocument.LoadXml,它将 文本 解析为 XML。

(顺便说一句,如果可能的话,我强烈建议更新为使用 XDocument。LINQ to XML 更好 XML API。 )