kingmercian
kingmercian

Reputation: 31

System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1 - Valid XML file?

I am receiving this error when trying to parse an xml from a byte array.

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

The failing code in question is:

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;
        }

And the XML it is failing to parse in hex is

3c3f786d6c2076657273696f6e3d22312e30223f3e3c4d6573736167653e3c5465726d696e616c547970653e45433530303c2f5465726d696e616c547970653e0d0a3c5465726d696e616c49443e313c2f5465726d696e616c49443e0d0a3c44657669636553657269616c4e6f3e6e756c6c65643c2f44657669636553657269616c4e6f3e0d0a3c526571756573743e4c6f67696e526571756573743c2f526571756573743e0d0a3c2f4d6573736167653e00

Which when converted to ASCII is:

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

I have removed the last two bytes 3e00 which I believe may be causing an invalid XML with no success.

Any help would be appreciated.

Upvotes: 3

Views: 13607

Answers (1)

Rahul Tripathi
Rahul Tripathi

Reputation: 172588

You can try like this:

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

The issue is called the Byte Order mark.

Upvotes: 1

Related Questions