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:44

You also should be carefull and avoid expressions like:

<e order="0" type="custom" name= "test">

The blank space that follows the name's equal could make your code crash

查看更多
Emotional °昔
3楼-- · 2019-04-03 08:45

Yes, you should delete the space between <? and 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>

Here's the relevant XML spec.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-04-03 08:45

My error in same case was that file wasn't saved as UTF-8.

查看更多
放荡不羁爱自由
5楼-- · 2019-04-03 08:48

Another common source of this error is when the XmlReader attempts to read your scripts as xml. That's a good reason to start commenting out scripts after the script tags. They will still run:

<script language="javascript" type="text/javascript">
<!--
    function myFunction() {
    }
    ...
-->
</script>
查看更多
时光不老,我们不散
6楼-- · 2019-04-03 08:50

Remove the first space in the document:

<?xml version="1.0" encoding="utf-8"?>
查看更多
狗以群分
7楼-- · 2019-04-03 08:55

I had a lot of errors because of this. Make sure you don't have spaces. There are two places I removed spaces that worked for me.

Was:

xmlns: xsi="http://www.w3.org/2001/XMLSchema-instance"

What worked:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

There was a space here too: < abc:def >. Remove all the spaces around the < and the >.

查看更多
登录 后发表回答