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

时间:2016-11-03 07:41:09

标签: .net xml invalid-characters

我正在尝试将网络响应转换为xml。但是,即使验证了xml字符串,当我尝试将响应字符串转换为XmlDocument时,我收到“无效字符错误”。我也在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;
}

在这两种情况下(在链接的answe中应用代码或不应用它),Xml字符串都是有效的。

你能建议任何其他解决方案吗?

1 个答案:

答案 0 :(得分:2)

您正在使用XmlDocument.Load,这意味着接受一个网址。我相信您打算使用XmlDocument.LoadXml文本解析为XML。

(另外,如果可能的话,我强烈建议更新以使用XDocument。LINQ to XML是一个更好的XML API。)