验证XML字符串内容包括使用C#进行编码

问题描述

| 我需要验证包含XML数据的字符串,不需要架构验证。我需要做的就是确保XML格式正确且编码正确。例如,我希望我的代码将这个XML代码段标识为无效:
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<parentNode> Positions1 ’</parentNode>
XMLDocument
中使用
LoadXML
方法不起作用,加载上面的代码段时不会引发任何错误。 我知道如果内容在XML文件中该怎么做,以下代码片段显示:
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ConformanceLevel = ConformanceLevel.Document;
readerSettings.CheckCharacters = true;
readerSettings.ValidationType = ValidationType.None;

xmlReader = XmlReader.Create(xmlFileName,readerSettings);
XmlDocument xdoc = new XmlDocument();
xdoc.Load(xmlReader);
因此,除了创建一个临时文件来写出我的xml字符串内容然后创建一个“ 4”实例来读取它之外,还有其他选择吗?如果有人可以在这个问题上指导我正确的方向,我将不胜感激。     

解决方法

        您还没有完全了解编码的含义。如果内存中有一个.Net字符串,则不再有\“原始数据\”并且因此没有编码。因此LoadXML有充分的理由。因此,您要做的根本没有任何意义。但是,如果您真的想要这样做: 您可以将字符串转换为内存中的流,因此无需编写临时文件。然后,可以在对XmlReader.Create的调用中使用该流而不是xmlFileName。     ,        阿齐姆 感谢您的详细答复,我终于能够提出一个适合我需要的解决方案。它涉及从\'unicode \'字符串中获取字节,然后将字节转换为utf8编码。
        try
        {
            byte[] xmlContentInBytes = new System.Text.UnicodeEncoding().GetBytes(xmlContent);

            System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false,true);
            utf8.GetChars(xmlContentInBytes);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return false;
        }
    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...