Ошибка name cannot begin with the character hexadecimal value

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.

asked Feb 17, 2010 at 16:35

Brian Hicks's user avatar

2

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.

answered Feb 17, 2010 at 16:37

Otávio Décio's user avatar

Otávio DécioOtávio Décio

73.4k17 gold badges161 silver badges228 bronze badges

1

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>

answered Mar 31, 2011 at 19:23

CZahrobsky's user avatar

CZahrobskyCZahrobsky

7447 silver badges7 bronze badges

0

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

answered Feb 17, 2010 at 16:38

High Performance Mark's user avatar

Remove the first space in the document:

<?xml version="1.0" encoding="utf-8"?>

answered Feb 17, 2010 at 16:37

SLaks's user avatar

SLaksSLaks

864k176 gold badges1901 silver badges1961 bronze badges

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

answered May 10, 2016 at 7:11

Migol's user avatar

MigolMigol

8,0918 gold badges47 silver badges69 bronze badges

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

answered Jun 25, 2018 at 13:39

Manuel Roldan's user avatar

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>

answered Mar 26, 2014 at 22:36

Keith Sirmons's user avatar

Keith SirmonsKeith Sirmons

8,26115 gold badges51 silver badges75 bronze badges

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 >.

answered Aug 14, 2015 at 21:50

raleign's user avatar

raleignraleign

1132 silver badges8 bronze badges

If in SSIS, just go to Solution Explorer, select the project then select «Rebuild Solution» from the Build menu option.

answered Sep 18, 2020 at 16:21

Jim's user avatar

JimJim

1851 silver badge5 bronze badges

  • Remove From My Forums
  • Question

  • I have a VB.NET project with several form objects included.  Last Friday, all of a sudden and without having added any new software to my computer, I can no longer open many of my form objects.  I get the message found in the subject of this post and the following Call Stack:

    at System.Xml.XmlTextReaderImpl.Throw(Exception e)
    at System.Xml.XmlTextReaderImpl.Throw(String res, String[] args)
    at System.Xml.XmlTextReaderImpl.Throw(Int32 pos, String res, String[] args)
    at System.Xml.XmlTextReaderImpl.ParseQName(Boolean isQName, Int32 startOffset, Int32& colonPos)
    at System.Xml.XmlTextReaderImpl.ParseElement()
    at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
    at System.Xml.XmlTextReaderImpl.Read()
    at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
    at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
    at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
    at System.Xml.XmlDocument.Load(XmlReader reader)
    at System.Xml.XmlDocument.Load(TextReader txtReader)
    at Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSerializer.Deserialize(DesignTimeSettings Settings, TextReader Reader, Boolean getRuntimeValue)
    at Microsoft.VisualStudio.Editors.SettingsGlobalObjects.SettingsFileGlobalObject.LoadSettings(String fileName)
    at Microsoft.VisualStudio.Editors.SettingsGlobalObjects.SettingsFileGlobalObject.BuildType()
    at Microsoft.VisualStudio.Editors.SettingsGlobalObjects.SettingsFileGlobalObject.GetObjectType()
    at Microsoft.VisualStudio.Shell.Design.GlobalType.get_ObjectType()
    at Microsoft.VisualStudio.Shell.Design.GlobalObject.GetHashCode()
    at Microsoft.VisualStudio.Shell.Design.GlobalObjectService.GlobalKey.GetHashCode()
    at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)
    at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
    at Microsoft.VisualStudio.Shell.Design.GlobalObjectService.GetGlobalObjects(Type baseType)
    at Microsoft.VisualStudio.Shell.Design.GlobalObjectService.GetGlobalObjects()
    at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetTypeFromGlobalObjects(String name, Boolean throwOnError, Boolean ignoreCase)
    at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
    at Microsoft.VisualStudio.Design.Serialization.CodeDom.AggregateTypeResolutionService.GetType(String name, Boolean throwOnError)
    at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.GetType(ITypeResolutionService trs, String name, Dictionary`2 names)
    at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.FillStatementTable(IDesignerSerializationManager manager, IDictionary table, Dictionary`2 names, CodeStatementCollection statements, String className)
    at System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, CodeTypeDeclaration declaration)
    at System.ComponentModel.Design.Serialization.CodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager manager)
    at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.PerformLoad(IDesignerSerializationManager serializationManager)
    at Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32 fReload)

    This is not the case on all my forms as some of them can still be opened.  Any modification to the form that can still be opened cannot be saved because upon a save, I get a very similar message:

    «Code generation for property ‘ContextMenu’ failed.  Error was ‘Name cannot begin with the ‘<‘ character, hexadecimal value 0x3C. Line 2, position 2.’The application runs fine, I just can’t open or change any of the forms.

Answers

  • Hi Mark,

    It looks like one or more XML files in your project were somehow corrupted. I can reproduce the error message in my own test project by manually corrupting the Settings.settings file if the Form (or its controls) has any properties bound to my application settings.

    So my suggestion is to check all the XML files that has any relations to your Form (like some properties bound to the settings or resources you’ve set in the designer previously), if you found any errors in these XML files, you can try fix them manually and see if the Form can be opened in designer again.

    Files like Application.myapp, *.resx, *.settings, *.config, *.xml.

    BTW, if you could let me know what version of Visual Studio you’re using, it would also be helpful to the troubleshooting.

    Thanks,

    Jie


    This posting is provided «AS IS» with no warranties, and confers no rights.
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Send us any feedback you have about the help from MSFT at fbmsdn@microsoft.com.

    The CodeFx Project
    My Blog (CHS)

    • Proposed as answer by

      Thursday, May 7, 2009 3:08 AM

    • Marked as answer by
      Jay_WangMicrosoft employee
      Wednesday, May 27, 2009 3:22 AM

Имя не может начинаться с символа »

Я разбираю XML в С#. Я получаю его из базы данных и поэтому конвертирую его в MemoryStream, прежде чем читать его с помощью XmlTextReader. Проблема в том, что я получаю эту ошибку: Name cannot begin with the ' ' character, hexadecimal value 0x20. Line 1, position 3. Ниже приведен мой XML и мой код для его чтения (он выходит из базы данных в порядке, без пустого первого символа). Любые предложения?

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>

С#:

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

Я думал, что это может быть кодировка, но я пробовал UTF8 и ASCII и ничего не могу найти.

17 фев. 2010, в 17:46

Поделиться

Источник

Да, вы должны удалить пробел между <? и 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>

Здесь соответствующая спецификация XML.

Otávio Décio
17 фев. 2010, в 17:32

Поделиться

Другим распространенным источником этой ошибки является то, что XmlReader пытается прочитать ваши скрипты как xml. Это хорошая причина начать комментирование скриптов после тегов script. Они все равно будут работать:

<script language="javascript" type="text/javascript">
<!--
    function myFunction() {
    }
    ...
-->
</script>

CZahrobsky
31 март 2011, в 20:04

Поделиться

Ваше сообщение об ошибке довольно явное, у вас есть ошибка в posn 3 в строке 1. Попробуйте <?xml — нет места.

High Performance Mark
17 фев. 2010, в 17:22

Поделиться

Удалите первое место в документе:

<?xml version="1.0" encoding="utf-8"?>

SLaks
17 фев. 2010, в 17:49

Поделиться

Моя ошибка в том же случае заключалась в том, что файл не был сохранен как UTF-8.

Migol
10 май 2016, в 08:46

Поделиться

Из-за этого у меня было много ошибок. Убедитесь, что у вас нет пробелов. Есть два места, где я удалял пробелы, которые работали для меня.

Был:

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

Что работало:

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

Здесь также было место: < abc: def > . Удалите все пробелы вокруг < и > .

raleign
14 авг. 2015, в 22:16

Поделиться

Я получал ту же ошибку, читающую XML файл.

Оказалось, что у меня был странствующий < в моем файле.

Я комментировал определенные дочерние узлы, и, стирая один из тегов комментариев, я оставил дополнительный < в файле. Появилось сообщение об ошибке «Имя не может начинаться с символа» r «, и этот вопрос был лучшим результатом Google для этого точного поиска.

<node>
    <!-- <child /> --><
    <child />
    <child />
</node>

Keith Sirmons
26 март 2014, в 23:09

Поделиться

Ещё вопросы

  • 1Автоматизировать установку ucbrowser
  • 0Первый пункт в моем выпадающем списке выделен
  • 0Как смоделировать нажатие клавиши или Keyup, когда ссылка нажата с помощью jQuery
  • 0Разве Redis не должен кэшировать записи в БД?
  • 0Angularjs — не в состоянии связывать данные с ngoptions
  • 1Scrapy пустой CSV-файл
  • 0Вызов URL-адреса неблокирующим способом на веб-странице
  • 0Проблемы при попытке применить класс CSS к строкам
  • 1Как исправить непредставляемый DateTime в C #
  • 1Возврат нужного значения в классе — Java
  • 1LightGBM — метрики классификации не могут обрабатывать смесь двоичных и непрерывных целей
  • 0Как анимировать размер этих вложенных элементов div? (JQuery)
  • 1Невозможно закрыть закрываемые вкладки и активировать вкладки
  • 0Сортировка результатов SQL для удобства чтения?
  • 0Выполните поиск, используя фильтр, но игнорируя знаки препинания
  • 0Ошибка Zend Framework 2: оператор не может быть выполнен при реализации функции year в табличном шлюзе
  • 1JavaScript — отправка электронной почты с использованием AWS SES
  • 0Как я могу получить навигационные ссылки для анимации, когда на них наведена мышь?
  • 0Numpy конвертировать из двоичной строки в массив с плавающей точкой
  • 0MySQL, используя сумму для столбца, чтобы получить общую сумму для каждой группы
  • 1Асинхронная загрузка в Azure не блокируется даже при вызове Task.WaitAll (задача)
  • 1Является ли View или ViewModel ответственным за преобразование данных из модели, представляемой в пользовательском интерфейсе?
  • 0@media не работает правильно для меня
  • 0Сделайте фон поля поиска кликабельным
  • 1Как совместить JLabel и JFrame?
  • 0Паспорт логин — mysql
  • 0Округление до 100 ед.
  • 1что означает name = «135» в кнопке в форме просмотра odoo 10
  • 0Код отслеживания не установлен (Google Analytics)
  • 0Выражение с участием модульных возведения в степень в C ++
  • 1Wikitude Передача значения из Java в JavaScript для использования в AR.RelativeLocation
  • 0Нахождение ранга булевой матрицы
  • 0Как добавить начальный ноль в jQueryUI Datepicker (внутри кода, не выводится)
  • 0JPA вернул объект, выбрасывающий внутреннюю ошибку сервера
  • 0Преобразовать целые числа в символы [дубликаты]
  • 0Пример проекта не запускается
  • 0Странный эффект сравнения строк PHP, это может быть сделано лучше?
  • 1Как отправить объекты разных классов в одном сообщении Json, чтобы их можно было десериализовать с помощью Gson?
  • 0Qt QML MenuBar и меню не отображаются
  • 0AngularJS — Что мне нужно делать вручную, когда я использую ngModelOptions allowInvalid = true?
  • 1чтение файла WAV в Java
  • 0Ширина и высота страницы заполнения холста
  • 0Не удалось запустить команду создания sql с mysqli_query php
  • 1Разбор массива JSON в объект Java
  • 0jqGrid с использованием navGrid с position = right не работает
  • 0Передать пользовательскую переменную в анонимную функцию щелчка jQuery
  • 0Слияние сортировки по структурам не работает
  • 0Ряды со столбцами в MySQL с логическими значениями
  • 1FindResource не работает в библиотеке пользовательских элементов управления
  • 0Создание пула объектов

Сообщество Overcoder

  • Hi ChairmanMichael,

    SQL Server is always using the UTF-16 encoding internally. Additionally, the explicit
    prolog is stripped out from any variable or column of XML data type.

    «…a 3rd party application I receive the error…», what application are you using?
    You can always open any XML file in the browser to check if it is a well-formed XML.

    1. It seems that you modified/simplified your original SQL to obfuscate some values.
      Please provide the real life example.
    2. Unfortunately, SSIS still doesn’t have XML Destination Adapter. I was asking for it since 2004, even before the very first version SSIS 2005 was released.
    3. That’s why it is better to use bcp utility to generate XML file on the file system.
      This method is very fast, and there is no string manipulations, pure XML is
      streamed
      to the file system:
    DECLARE @SQLCmd VARCHAR(8000)
    	, @outputFileName VARCHAR(256) = 'e:TempSampleXMLOutput.xml'
    	, @bcp VARCHAR(256) = 'c:Program FilesMicrosoft SQL ServerClient SDKODBC130ToolsBinnbcp.exe'
    	, @SQL VARCHAR(2048) = 'SET NOCOUNT ON; SELECT TOP(1) TABLE_SCHEMA, TABLE_NAME FROM master.Information_Schema.Tables FOR XML PATH(''r''), TYPE, ROOT(''root'');';
    
    -- SQL Server 2016 and later (it works even in 2012 but undocumented)
    SET @SQLCmd = FORMATMESSAGE('START "" "%s" "%s" queryout "%s" -T -x -c -C 1252 -a 32768 -S %s'
    				, @bcp
    				, @SQL
    				, @outputFileName
    				, @@SERVERNAME);
    
    -- just to see it
    SELECT @SQLCmd AS [Command to execute];
    
    -- create the XML file on the file system
    EXECUTE master.sys.xp_cmdshell @SQLCmd;

    Simulation of your SQL, and it is working:

    DECLARE @tbl TABLE(field1 VARCHAR(30)); INSERT INTO @tbl VALUES ('some value'); DECLARE @XMLOutput XML; DECLARE @XMLOutputChar nvarchar(max) ;WITH XMLNAMESPACES('myNameSpace' as ns) SELECT @XMLOutput = ( SELECT field1 FROM @tbl FOR XML PATH('Testing'),TYPE, ROOT('TestingLoader'),ELEMENTS XSINIL ); SET @XMLOutputChar = '<?xml version="1.0" encoding="UTF-16"?>' + CONVERT(nvarchar(max),@XMLOutput); SELECT @XMLOutputChar AS XMLOutput;

    SELECT CAST(@XMLOutputChar AS XML);

    Output as NVARCHAR:

    XMLOutput
    <?xml version="1.0" encoding="UTF-16"?><TestingLoader xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns="myNameSpace"><Testing><field1>some value</field1></Testing></TestingLoader>

    Output as XML:

    <TestingLoader xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns="myNameSpace">
      <Testing>
        <field1>some value</field1>
      </Testing>
    </TestingLoader>
    • Edited by

      Tuesday, July 30, 2019 6:07 PM

    • Marked as answer by
      ChairmanMichael
      Wednesday, July 31, 2019 7:34 AM

  • See more:

    My coading is given below

    <% @ Import NameSpace="System.Data"%>
    <% @ Page Language="VB" Debug="true"%>
    <Script  runat="server">
    Sub Page_Load
    if not Page.IsPostBack then
    dim mycountries = New Dataset
    mycountries.Readxml(MapPath("countries.xml"))
    rb.DataSource = mycountries
    rb.DataValueField = "value"
    rb.DataTextField = "Text"
    rb.DataBind()
    End if
    End Sub
    Sub displayMassage (s As object, e As EventArgs)
    Lbl1.Text = "Your Favourite Country is:" & rb.SelectedItem.Text
    End Sub
    </script>
    <html>
    <head>
    <title>Hashtable with XML File</title>
    </head>
    <body>
    <form  runat="server">
    <asp:CheckBoxList id = "rb" runat = "server" AutoPostBack = "True" onSelectedIndexChanged = "displayMassage"/>
    <p>
    <asp:Label id = "Lbl1" runat = "server"/>
    </p>
    </form>
    </body>
    </html>

    And My XML file’s containts is given below

    <? xml version = "1.0" encoding = "ISO-8859-1"?>
    <countries>
    <country>
    <text>Norway</text>
    <value>N</value>
    </country>
    <country>
    <text>Sweden</text>
    <value>S</value>
    </country>
    <country>
    <text>France</text>
    <value>F</value>
    </country>
    <country>
    <text>Italy</text>
    <value>I</value>
    </country>
    </countries>


    It contains space at the 3rd char in the 1st line.

    Please remove it

    <?xml version = "1.0" encoding = "ISO-8859-1"?>

    use the above line

    This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

    CodeProject,
    20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
    +1 (416) 849-8900

    Понравилась статья? Поделить с друзьями:
  • Ошибка n20 на стиральной машине indesit
  • Ошибка n20 на стиральной машине hotpoint ariston
  • Ошибка n20 в стиральной машине аристон
  • Ошибка n102006 guns of glory
  • Ошибка n1 12 доступа к файлу конфигурации профиля diopost