【问题标题】:System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1 - Valid XML file?System.Xml.XmlException:根级别的数据无效。第 1 行,位置 1 - 有效的 XML 文件?
【发布时间】:2018-08-02 08:23:35
【问题描述】:

我在尝试从字节数组解析 xml 时收到此错误。

System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1

有问题的失败代码是:

public Packet PacketProcessor(Packet packet, out DeviceVerifyStep step, out string device_model, out string device_sn)
    {
        step = DeviceVerifyStep.None;
        device_model = null;
        device_sn = null;

        XmlDocument doc = new XmlDocument();
        try
        {
            string msg_xml = Encoding.ASCII.GetString(packet.body);
            Console.WriteLine(msg_xml);
            doc.LoadXml(msg_xml);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return null;
        }

它无法以十六进制解析的 XML 是

3c3f786d6c2076657273696f6e3d22312e30223f3e3c4d6573736167653e3c5465726d696e616c547970653e45433530303c2f5465726d696e616c547970653e0d0a3c5465726d696e616c49443e313c2f5465726d696e616c49443e0d0a3c44657669636553657269616c4e6f3e6e756c6c65643c2f44657669636553657269616c4e6f3e0d0a3c526571756573743e4c6f67696e526571756573743c2f526571756573743e0d0a3c2f4d6573736167653e00

转换成ASCII的时候是:

<?xml version="1.0"?><Message><TerminalType>EC500</TerminalType>
<TerminalID>1</TerminalID>
<DeviceSerialNo>nulled</DeviceSerialNo>
<Request>LoginRequest</Request>
</Message>?

我已删除最后两个字节 3e00,我认为这可能会导致无效的 XML 没有成功。

任何帮助将不胜感激。

【问题讨论】:

  • 去掉十六进制字符串末尾的00

标签: c# xml


【解决方案1】:

正如blog 中的建议,您可以这样尝试:

string msg_xml = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(msg_xml))
{
    xml = xml.Remove(0, msg_xml.Length);
}

这个问题被称为Byte Order mark

【讨论】:

  • 在 OP 给出的示例中,这会去哪里?
猜你喜欢
  • 2020-10-30
  • 1970-01-01
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 2011-10-28
  • 1970-01-01
相关资源
最近更新 更多