Name cannot begin with the ' ' character

2019-04-03 08:28发布

I'm parsing some XML in C#. I'm getting it from a database, and so converting it to a MemoryStream before reading it with an XmlTextReader. The problem is that I get this error: Name cannot begin with the ' ' character, hexadecimal value 0x20. Line 1, position 3. Following is my XML and my code for reading it (it's coming out of the database alright, no blank first character). Any suggestions?

XML:

<? xml version="1.0" encoding="utf-8" ?>
<form>
   <e order="0" type="custom" name="test">
      <fi type="text" />
      <o />
   </e>
   <e order="1" type="zip" />
   <e order="2" type="state" />
</form>

C#:

byte[] byteArray = new byte[formXml.Length];
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byteArray = encoding.GetBytes(formXml);
MemoryStream xmlStream = new MemoryStream(byteArray);

XmlTextReader xmlReader = new XmlTextReader(xmlStream);
while (xmlReader.Read())
{
    if (xmlReader.HasValue)
    {
        returnString += xmlReader.Depth.ToString();
    }
}

I thought it could be the encoding, but I've tried by UTF8 and ASCII and can't find anything.

8条回答
神经病院院长
2楼-- · 2019-04-03 08:56

Your error message is quite explicit, you have an error at posn 3 in line 1. Try <?xml -- no space.

查看更多
在下西门庆
3楼-- · 2019-04-03 09:00

I was getting the same error reading an XML file.

It turned out I had an errant < character in my file.

I was commenting out certain child nodes and when erasing one of the comment tags, I left an extra < in the file. The error message came back "Name cannot begin with the '\r' character" and this question was the top google result for that exact search.

<node>
    <!-- <child /> --><
    <child />
    <child />
</node>
查看更多
登录 后发表回答