Data at the root level is invalid line 1 position 1 что за ошибка

XML.LoadData — данные на корневом уровне недопустимы. Строка 1, Позиция 1

Я пытаюсь проанализировать некоторый XML внутри установщика WiX. XML будет объектом всех моих ошибок, возвращаемых с веб-сервера. Я получаю ошибку в заголовке вопроса с этим кодом:

XmlDocument xml = new XmlDocument();
try
{ xml.LoadXml(myString);
}
catch (Exception ex)
{ System.IO.File.WriteAllText(@"C:text.txt", myString + "rnrn" + ex.Message); throw ex;
}

myString это (как видно из вывода text.txt)

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

text.txt выходит выглядит так:

<?xml version="1.0" encoding="utf-8"?>
<Errors></Errors>
Data at the root level is invalid. Line 1, position 1.

мне нужен этот XML для анализа, чтобы я мог видеть, были ли у меня какие-либо ошибки.

этот вопрос не является дубликатом, как отмечено. В этом вопросе человек, задающий вопрос, использовал LoadXml для анализа XML-файла. Я разбираю строку, которая является правильным использованием LoadXml

ответов


скрытый символ, вероятно, является BOM.
Объяснение проблемы и решение можно найти здесь, кредиты на Джеймса Шуберта, в зависимости от ответа Джеймс Brankin нашел здесь.

хотя предыдущий ответ удаляет скрытый символ, он также удаляет всю первую строку. Более точная версия была бы:

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

я столкнулся с этой проблемой при извлечении файла XSLT из Azure blob и загрузке его в Объект XslCompiledTransform.
На моей машине файл выглядел просто отлично, но после загрузки его как blob и возврата его, был добавлен символ BOM.



проблема здесь была в том, что myString была эта строка заголовка. Либо в начале первой строки был какой-то скрытый символ, либо сама строка вызывала ошибку. Я отрезал первую строчку вот так:—3—>

xml.LoadXml(myString.Substring(myString.IndexOf(Environment.NewLine)));

это решило мою проблему.


Я думаю, что проблема заключается в кодировании. Вот почему удаление первой строки (с байтом кодирования) может решить проблему.

мое решение для данные на корневом уровне, является недействительным. Строка 1, Позиция 1.
в XDocument.Parse(xmlString) заменял его на XDocument.Load( new MemoryStream( xmlContentInBytes ) );

Я заметил, что моя строка xml выглядела нормально:

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

но в другой кодировке текстового редактора это выглядело так:

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

надеюсь, это поможет


XmlDocument configurationXML = new XmlDocument();
List<byte> byteArray = new List<byte>(webRequest.downloadHandler.data);
foreach(byte singleByte in Encoding.UTF8.GetPreamble())
{ byteArray.RemoveAt(byteArray.IndexOf(singleByte));
}
string xml = System.Text.Encoding.UTF8.GetString(byteArray.ToArray()); xml = xml.Replace("\r", ""); xml = xml.Replace("\t", "");

сохраните файл с другой кодировкой:

в VS 2017 вы найдете кодировку в виде выпадающего списка рядом с кнопкой Сохранить.


Если ваш xml находится в строке, используйте следующее, Чтобы удалить любую метку порядка байтов:

 xml = new Regex("\<\?xml.*\?>").Replace(xml, "");

Я нашел одно из решений.
Для вашего кода, это может быть следующим образом —

XmlDocument xml = new XmlDocument();
try
{ // assuming the location of the file is in the current directory // assuming the file name be loadData.xml string myString = "./loadData.xml"; xml.Load(myString);
}
catch (Exception ex)
{ System.IO.File.WriteAllText(@"C:\text.txt", myString + "\r\n\r\n" + ex.Message); throw ex;
}


Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Answered by:

Data at the root level is invalid line 1 position 1 что за ошибка

Question

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

string XmlizedString = string.Empty;
MemoryStream MemStream = new MemoryStream();
XmlSerializer s = new XmlSerializer(typeof(NLCompany.Company));
XmlTextWriter XmlTxtWriter = new XmlTextWriter(MemStream, new UTF8Encoding() );

What is the difference between using ‘ new UTF8Encoding()’ and ‘ Encoding.UTF8’ in the XmlTextWriter constructor?

Answers

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

The hex value you see sets the byte ordering mark of the text. If you are using UTF8, should be 3 characters long and of value 0xEFBBBF. You can actually see it by calling Encoding.UTF8.GetPreamble().

I searched more thoroughly, and there is actually a difference between the two calls you were making:

Encoding.UTF8 returns a new instance of UTF8Encoding(true), so you get an encoder that use the preamble of UTF8 for all encoding operation.

When you called UTF8Encoding(), the default is to call UTF8Encoding(false), which does not use the preamble of UTF8 for encoding operation. (the preamble will then be an empty byte array)

So when you used Encoding.UTF8, the preamble was emitted, rendering your data invalid.

Hope that helps clarify what is happening!

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

string XmlizedString = string .Empty;

MemoryStream MemStream = new MemoryStream ();

XmlTextWriter XmlTxtWriter = new XmlTextWriter (MemStream, Encoding .UTF8 /*new UTF8Encoding()*/ );

MemStream.Write(b, 0, b.Length);

XmlDocument XmlDoc = new XmlDocument ();

XmlDoc.LoadXml( UnicodeEncoding .UTF8.GetString(MemStream.ToArray()));

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

The hex value you see sets the byte ordering mark of the text. If you are using UTF8, should be 3 characters long and of value 0xEFBBBF. You can actually see it by calling Encoding.UTF8.GetPreamble().

I searched more thoroughly, and there is actually a difference between the two calls you were making:

Encoding.UTF8 returns a new instance of UTF8Encoding(true), so you get an encoder that use the preamble of UTF8 for all encoding operation.

When you called UTF8Encoding(), the default is to call UTF8Encoding(false), which does not use the preamble of UTF8 for encoding operation. (the preamble will then be an empty byte array)

So when you used Encoding.UTF8, the preamble was emitted, rendering your data invalid.

Hope that helps clarify what is happening!

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Thanks to Chris for useful info here

When i tried to load some XML files which are stored in different formats (using different encoding such as ANSI, UTF8 and UNICODE), the XmlDocument.Load(..) causes some similar problem. There are different preambles at the begining of files causing XML parser to complain/fail. Only ANSI format XML files get loaded/parsed correctly. The byte order mark is different at the beginning of files for different-format files,

Дополнительно:  Antonymy. Classification of Antonyms

1) ANSI XML files have no preamble.
2) UTF8 XML files have preamble like «0xEFBBBF».
3) UNICODE- XML files have the preamble of «0xFFFE» encoding for byte order mark.

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Hi Steve, so then how did you go about successfully loading UTF8 and UNICODE XML files?

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

If the first line of your XML file specifies UTF8, you need to save this file as ANSI format in a notepad to eliminate the preamble.

If the first line of your XML file specifies UTF16, you need to save this file as UNICODE format in a notepad.

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

Hi Steve, sorry to come back on this, but how do you know whether the first line of XML specifies either UTF8 or UTF16?

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

If you have to ask, then it probably specifies neither. He means if it starts like this:

xml version = «1.0» encoding = «utf-8» ?>

  • Edited by John Saunders Moderator Saturday, May 31, 2008 4:26 AM Fix code block

Data at the root level is invalid line 1 position 1 что за ошибка

Data at the root level is invalid line 1 position 1 что за ошибка

I have same problem while calling SP from code behind. Here, is SP.

It creates Xml like :

I think, the problem in lack of Xml declaration in above Xml result.

Server Error in ‘/’ Application.

Parser Error

Parser Error Message: Data at the root level is invalid. Line 1, position 1.

Source File: /App_Browsers/compat.browser Line: 1

Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210

Also getting this

Privileges: —
Restricted Sid Count: 0
Access Mask: 0x94

Application information:
Application domain: /LM/W3SVC/1032202749/Root-7-128196688021727606
Trust level: WSS_Minimal
Application Virtual Path: /
Application Path: C:\Inetpub\wwwroot\wss\VirtualDirectories\80\
Machine name: *****

Process information:
Process ID: 3804
Process name: w3wp.exe
Account name: *****\dealer

Exception information:
Exception type: HttpException
Exception message: Data at the root level is invalid. Line 1, position 1.

Thread information:
Thread ID: 1
Thread account name: *****\dealer
Is impersonating: False
Stack trace: at System.Web.Compilation.BuildManager.ReportTopLevelCompilationException()
at System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
at System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters)

Custom event details:

I would like to meet the person that made this part of the system work as it does. I fixed this error I would think many people might have this over time.

Idea of what could be the issues was only found here.

In doing some editting on the intranet site which is WSS v3 I openned a file called web.config from the c:\inetpub\wwwroot\wss\virutaldirectories\80

Just openning the file seems to be enough to have the system create a sub folder called _vti_pvt or something like that. In trouble shoot this error I openned a few files and it created this folder and made a copy of each file I openned and put it in a sub folder with the same name I found 6 of these folders all new. I guess this file is not a true xml file and made the whole site crash for 2 hours.

I deleted these directories and everything worked right away.

The person that set this up should be shot.

xmlDoc.LoadXml(inputXml);
 public static int spGetTaxOfficeXML(SqlXml _inputXml) { // this procedure rename Row elements name with NodeName attribute value string inputXml = _inputXml.ToString(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(inputXml);
// procedure Logic SqlContext.Pipe.Send(inputXml); return 0; }

it works well, when the XML text is inside variable inside visual studio as a text. But when i upload code to the SQL server as CLR, and try to execute it from SQL Management Studio:

DECLARE @XML XML
SET @XML = '<NodeA><NodeB></NodeB><NodeC AttributeX=""><Row NodeName="RowA" AttributeA="" AttributeB="abcd" AttributeC="efgh" /><Row NodeName="RowB" AttributeA="wxyz" /><Row NodeName="RowC" AttributeB="qwer" AttributeC="tyui" /><Row NodeName="RowD" AttributeA="stuv" AttributeB="erty" AttributeC="fghj" /></NodeC></NodeA>'
EXEC dbo.spGetTaxOfficeXML @XML

then this error is throwed:

Msg 6522, Level 16, State 1, Procedure spGetTaxOfficeXML, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate "spGetTaxOfficeXML":
System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.
System.Xml.XmlException: at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) at System.Xml.XmlDocument.Load(XmlReader reader) at System.Xml.XmlDocument.LoadXml(String xml) at StoredProcedures.spGetTaxOfficeXML(String inputXml)
// if byte mark exception happens string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); if (inputXml.StartsWith(_byteOrderMarkUtf8)) { inputXml = inputXml.Remove(0, _byteOrderMarkUtf8.Length); }

What is wrong here ?

Solution 1

I eventually figured out there was a byte mark exception and removed it using this code:

 string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); if (xml.StartsWith(_byteOrderMarkUtf8)) { var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1; xml = xml.Remove(0, lastIndexOfUtf8); }

Solution 2

I can give you two advices:

  1. It seems you are using «LoadXml» instead of «Load» method. In some cases, it helps me.
  2. You have an encoding problem. Could you check the encoding of the XML file and write it?

Solution 3

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

Sometimes, there is some «invisible» (not visible in all text editors). Some programs add this.

Solution 4

if you are using XDocument.Load(url); to fetch xml from another domain, it’s possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException

See my solution to this eventuality here:
XDocument.Load(feedUrl) returns «Data at the root level is invalid. Line 1, position 1.»

Solution 5

Using StreamReader created with 2nd constructor parameter detectEncodingFromByteOrderMarks set to true, will determine proper encoding and create string which does not break XmlDocument.LoadXml method.

public string GetXmlString(string url)
{ using var stream = GetResponseStream(url); using var reader = new StreamReader(stream, true); return reader.ReadToEnd(); // no exception on `LoadXml`
}
public string GetXmlString(string url)
{ byte[] bytes = GetResponseByteArray(url); return System.Text.Encoding.UTF8.GetString(bytes); // potentially exception on `LoadXml`
}

So, in the case of your third party library, they probably use 2nd approach to decode XML stream to string, thus the exception.

Дополнительно:  6 Things You Need to Know About a Front Tooth Root Canal

Comments

  • I am using a third-party DLL which transmits an XML document over the internet.

    Data at the root level is invalid. Line 1, position 1. (see below for
    full exception text.)

    Here are the first few lines of the XML Document:

    <?xml version="1.0" encoding="utf-8"?> <REQUEST> <HEADER> <REQUESTID>8a5f6d56-d56d-4b7b-b7bf-afcf89cd970d</REQUESTID> <MESSAGETYPE>101</MESSAGETYPE> <MESSAGEVERSION>3.0.2</MESSAGEVERSION>
    System.ApplicationException was caught Message=Unexpected exception. Source=FooSDK StackTrace: at FooSDK.RequestProcessor.Send(String SocketServerAddress, Int32 port) at Foo.ExecuteRequest(Int32 messageID, IPayload payload, Provider prov) at Foo.SendOrder(Int32 OrderNo) InnerException: System.Xml.XmlException LineNumber=1 LinePosition=1 Message=Data at the root level is invalid. Line 1, position 1. Source=System.Xml SourceUri="" StackTrace: at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String arg) at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) at System.Xml.XmlDocument.Load(XmlReader reader) at System.Xml.XmlDocument.LoadXml(String xml) at XYZ.RequestProcessor.GetObjectFromXML(String xmlResult) at XYZ.RequestProcessor.Send(String SocketServerAddress, Int32 port) InnerException:

C# Problem Overview


I’m trying to parse some XML inside a WiX installer. The XML would be an object of all my errors returned from a web server. I’m getting the error in the question title with this code:

 xml new ();
{	xml.(myString);
} ( ex)
{	...(@, myString ex.); ex;
}

myString is this (as seen in the output of text.txt)

<?xml version= encoding=?>

text.txt comes out looking like this:

<?xml version= encoding=?>Data at the root level is invalid. Line 1, position 1.

I need this XML to parse so I can see if I had any errors.

C# Solutions


Solution 1 — C#

The hidden character is probably BOM.
The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.

Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:

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

I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object.
On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.

Solution 2 — C#

Use Load() method instead, it will solve the problem. See more

Solution 3 — C#

The issue here was that myString had that header line. Either there was some hidden character at the beginning of the first line or the line itself was causing the error. I sliced off the first line like so:

xml.LoadXml(myString.Substring(myString.IndexOf(Environment.NewLine)))

This solved my problem.

Solution 4 — C#

I Think that the problem is about encoding. That’s why removing first line(with encoding byte) might solve the problem.

My solution for Data at the root level is invalid. Line 1, position 1.
in XDocument.Parse(xmlString) was replacing it with XDocument.Load( new MemoryStream( xmlContentInBytes ) );

I’ve noticed that my xml string looked ok:

<?xml version= encoding=?>

but in different text editor encoding it looked like this:

?<?xml version= encoding=?>

Hope it will help

Solution 5 — C#

Save your file with different encoding:

In VS 2017 you find encoding as a dropdown next to Save button.

Solution 6 — C#

XmlDocument = new XmlDocument()
List<byte> = new List<byte>(webRequest.downloadHandler.data)
foreach(byte singleByte in Encoding.UTF8.GetPreamble())
{ byteArray.RemoveAt(byteArray.IndexOf(singleByte))
}
string = System.Text.Encoding.UTF8.GetString(byteArray.ToArray()) = xml.Replace(, ) = xml.Replace(, )

Solution 7 — C#

Using StreamReader created with 2nd constructor parameter detectEncodingFromByteOrderMarks set to true, will determine proper encoding and create string which does not break XmlDocument.LoadXml method.

 (){ stream = GetResponseStream(url); reader = StreamReader(stream, ); reader.ReadToEnd(); // no exception on `LoadXml`}
 (){ [] bytes = GetResponseByteArray(url); System.Text.Encoding.UTF8.GetString(bytes); // potentially exception on `LoadXml`}

Solution 8 — C#

 = new Regex().Replace(xml, )

Solution 9 — C#

At first I had problems escaping the «&» character, then diacritics and special letters were shown as question marks and ended up with the issue OP mentioned.

using System.IO.Stream instead of string solved all the issues for me.

var = await this.httpClient.GetAsync(url)
var = await response.Content.ReadAsStreamAsync()
var = new XmlDocument()
xmlDocument.Load(responseStream)

The cool thing about Load() is that this method automatically detects the string format of the input XML (for example, UTF-8, ANSI, and so on). See more

Solution 10 — C#

 xml new ();
{ // assuming the location of the file is in the current directory  // assuming the file name be loadData.xml string myString ; xml.(myString);
} ( ex)
{ ...(@, myString ex.); ex;
}

Solution 11 — C#

Я использую стороннюю DLL, которая передает XML-документ через Интернет.

Почему DLL выбрасывает следующее исключение?

Данные на корневом уровне недействительны. Строка 1, позиция 1. (см. Ниже полный текст исключения.)

Вот первые несколько строк документа XML:

<?xml version="1.0" encoding="utf-8"?> <REQUEST> <HEADER> <REQUESTID>8a5f6d56-d56d-4b7b-b7bf-afcf89cd970d</REQUESTID> <MESSAGETYPE>101</MESSAGETYPE> <MESSAGEVERSION>3.0.2</MESSAGEVERSION>
System.ApplicationException was caught Message=Unexpected exception. Source=FooSDK StackTrace: at FooSDK.RequestProcessor.Send(String SocketServerAddress, Int32 port) at Foo.ExecuteRequest(Int32 messageID, IPayload payload, Provider prov) at Foo.SendOrder(Int32 OrderNo) InnerException: System.Xml.XmlException LineNumber=1 LinePosition=1 Message=Data at the root level is invalid. Line 1, position 1. Source=System.Xml SourceUri="" StackTrace: at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String arg) at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read() at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) at System.Xml.XmlDocument.Load(XmlReader reader) at System.Xml.XmlDocument.LoadXml(String xml) at XYZ.RequestProcessor.GetObjectFromXML(String xmlResult) at XYZ.RequestProcessor.Send(String SocketServerAddress, Int32 port) InnerException:



Ответ 1

В конце концов я понял, что существует исключение байтовой метки и удалено с помощью этого кода:

 string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); if (xml.StartsWith(_byteOrderMarkUtf8)) { var lastIndexOfUtf8 = _byteOrderMarkUtf8.Length-1; xml = xml.Remove(0, lastIndexOfUtf8); }

Ответ 2

Я могу дать вам два совета:

  • Кажется, вы используете «LoadXml» вместо метода «Загрузить». В некоторых случаях это помогает мне.
  • У вас проблема с кодировкой. Не могли бы вы проверить кодировку XML файла и записать его?
Дополнительно:  Не включается ноутбук: как восстановить его работу. Почему ноутбук не включается и не загружается: все способы решения проблемы

Ответ 3

Удалите все до <?xml version="1.0" encoding="utf-8"?>

Иногда существует некоторая «невидимая» (не видимая во всех текстовых редакторах). Некоторые программы добавляют это.

Он называется BOM, вы можете прочитать об этом здесь: https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding

Ответ 4

если вы используете XDocument.Load(url); для извлечения xml из другого домена, возможно, что хост отклонит результат запроса и возврата и неожиданный (не-xml) результат, который приведет к описанному выше XmlException

Смотрите мое решение этой возможности здесь:
XDocument.Load(feedUrl) возвращает » Данные на корневом уровне недействительны. Строка 1, позиция 1. «

Ответ 5

Все, что я сделал, это заменить все смешные символы следующим образом:

Возникла задача загрузить из XML справочник контрагентов. Структура к сожелению не из конфы по обмену.

пока для чтения копаю Книга знаний: Применение XSL запросов при организации доступа к данным XML файла из 1С (7.7+V7plus.dll) XLT

что лучше использовать для записи ?

Так. Походу пока сам не напишешь, никто не напишет 🙁
Эх, интересно есть конфигуратор в виде окошка отправки сообщения с мисты ?

(1) чего конфигуратор?

(4) Слишком много ограничений на формат. Неизвестно каком файл передадут, а влиять на ту сторону возможности нет.
Щас пока читаю http://www.sql.ru/articles/mssql/03102702XMLIn20Minutes.shtml

(6) Спс. Щас гляну.
Вопрос:
<?xml version=»1.0″ encoding=»utf-8″?>
<RESPONSE VERSION=»1.0.0″ xmlns=»» xmlns:xsi=»http://www.w3.org/2001/XMLSchema-instance» xsi:noNamespaceSchemaLocation=»send.xsd»>
Кодировка здесь «utf-8» ?
Если должна быть кодировка windows-1251, что должно стоять ?
а то ворд у меня тока теги показывает — без данных

(7) <?xml version=»»1.0″» encoding=»»windows-1251″» ?>

Не, win word не хочет открывать, ругается что проблема с кодировкой

Придется с DOM трахаться. блин.

а что v7plus не устраивает

Точно. utf-8
но по регламенту должон быть в win-1251
«представляются в виде файлов формата XML в кодировке Windows-1251. »
при этом схема прописана «<?xml version=»1.0″ encoding=»UTF-8″ ?>»
а можно из 1с работать с XMLTextReader ?

(16) Да, см. 14

А он ищет сам тег или надо считывать теги в таком порядке каком они есть ?

(18) Надо читать в том порядке, в котором они есть.
Короче как в 8-ке.
Имя тега указывать не обязательно.

Если пишет ошибку, попробуй открыть файл в Internet Explorer.
Если не откроется, то там какая-то неполадка в самом XML.

Пытаемся перейти на новый формат для приказа №820, пытаемся отправлять те же данные, что и раньше, но с новым методом GenerateSenderTitleXml.
Вызываем данный метод с параметрами, передаем в JSON.

{ "boxId" => "103a03582e0c4d74b05c617f124564dc@diadoc.ru", "documentTypeNamedId" => "UniversalTransferDocument", "documentFunction" => "СЧФДОП", "documentVersion" => "utd820_05_01_01", "titleIndex" => "0"
}

в теле запроса передаем:

{ "Function" => "СЧФДОП", "DocumentDate" => "09.10.2017", "DocumentNumber" => "П-32821/219", "Seller" => { "BoxId" => "103a03582e0c4d74b05c617f124564dc@diadoc.ru", "OrgName" => "Общество с ограниченной ответственностью «Инсейлс Рус»", "Inn" => "7714843760", "Kpp" => "771401001", "Address" => { "RussianAddress" => { "ZipCode" => "125319", "Region" => "77", "City" => "Москва", "Street" => "ул Академика Ильюшина", "Building" => "дом 4", "Block" => "кор. 1", "Apartment" => "офис 11" } }, "FnsParticipantId" => "2BM-7714843760-771401001-201407070405496642694", "OrgType" => "1", "Okopf" => "12300", "Okpo" => "92547290", "Phone" => "(495) 649-83-14", "Email" => "docs@insales.ru", "CorrespondentAccount" => "30101810200000000700", "BankAccountNumber" => "40702810700001450673", "BankName" => "АО \"РАЙФФАЙЗЕНБАНК\"", "BankId" => "044525700" }, "Buyer" => { "BoxId" => "36bbf987214c4e91be11a6b6bb2a1660@diadoc.ru", "OrgName" => "Общество с ограниченной ответственностью \"Умный Ритейл\"", "Inn" => "7811657720", "Kpp" => "781101001", "Address" => { "RussianAddress" => { "ZipCode" => "192019", "Region" => "78", "City" => nil, "Territory" => nil, "Street" => "ул Седова", "Building" => "11", "Block" => "А", "Apartment" => "627" } }, "FnsParticipantId" => "2BM-7811657720-781101001-201911211209267911354", "OrgType" => "1", "Phone" => "89214284838", "Email" => "store@smart.space", "CorrespondentAccount" => "30101810600000000786", "BankAccountNumber" => "40702810032410001505", "BankName" => "Филиал «Санкт-Петербургский» АО «АЛЬФА-БАНК»", "BankId" => "044030786" }, "Shipper" => { "SameAsSeller" => true }, "Consignee" => { "BoxId" => "36bbf987214c4e91be11a6b6bb2a1660@diadoc.ru", "OrgName" => "Общество с ограниченной ответственностью \"Умный Ритейл\"", "Inn" => "7811657720", "Kpp" => "781101001", "Address" => { "RussianAddress" => { "ZipCode" => "192019", "Region" => "78", "City" => nil, "Territory" => nil, "Street" => "ул Седова", "Building" => "11", "Block" => "A", "Apartment" => "627" } }, "FnsParticipantId" => "2BM-7811657720-781101001-201911211209267911354", "OrgType" => "1", "Phone" => "89214284838", "Email" => "store@smart.space", "CorrespondentAccount" => "30101810600000000786", "BankAccountNumber" => "40702810032410001505", "BankName" => "Филиал «Санкт-Петербургский» АО «АЛЬФА-БАНК»", "BankId" => "044030786" }, "Signers" => [ [0] { "BoxId" => "103a03582e0c4d74b05c617f124564dc@diadoc.ru", "SignerDetails" => { "Surname" => "Горшков", "FirstName" => "Тимофей", "JobTitle" => "Генеральный директор", "Inn" => "7714843760", "SignerType" => "1", "SignerOrganizationName" => "Общество с ограниченной ответственностью «Инсейлс Рус»", "SignerPowers" => "0", "SignerStatus" => "1" } } ], "PaymentDocuments" => [ [0] { "DocumentDate" => "06.10.2017", "DocumentNumber" => "4" } ], "InvoiceTable" => { "Items" => [ [0] { "Product" => "Неисключительные права на Программу для ЭВМ \"Платформа InSales\" тариф \"Стандартный\" на срок с 09.10.2017 по 31.10.2017", "TaxRate" => 0, "Vat" => "0,00", "SubtotalWithVatExcluded" => "1276.13", "Subtotal" => "1276.13" } ], "Vat" => "0,00", "Total" => "1276.13" }, "Currency" => "643", "TransferInfo" => { "OperationInfo" => "Права переданы", "TransferDate" => "09.10.2017", "Employee" => { "EmployeePosition" => "Генеральный директор", "TransferSurname" => "Горшков", "TransferFirstName" => "Тимофей" }, "TransferBase" => [ [0] { "BaseDocumentName" => "Договор", "BaseDocumentNumber" => 219394, "BaseDocumentDate" => "02.10.2017" } ] }, "DocumentCreator" => "Общество с ограниченной ответственностью «Инсейлс Рус»"
}

В ответ получаем ошибку

Invalid data UserContractData:\r\nData at the root level is invalid. Line 1, position 1

Подскажите, пожалуйста, что делаем не так.

Оцените статью
Master Hi-technology