尝试从字节数组中解析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失败,并没有成功。
任何帮助将不胜感激。
答案 0 :(得分:1)
按照此blog中的建议,您可以尝试如下操作:
string msg_xml = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(msg_xml))
{
xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}
该问题称为Byte Order mark。