Фатальная ошибка starttag invalid element name

Привет форумчане!Пытаюсь загрузить данные из XML в 1С. Вылетает с такой ошибкой:

Ошибка при вызове метода контекста (Прочитать)

                    Пока Файл.Прочитать() Цикл

по причине:

Ошибка разбора XML:  — [9,6]

Фатальная ошибка:

StartTag: invalid element name

В самом файле XML как раз на цифровой тег ругается, руками если поправить на любое другое имя не числовое, грузит нормально тогда.

<?xml version=’1.0′ encoding=’windows-1251′?>

<root>

<header>

    <fileName>тут был путь к файлу</fileName>

    <fileNumber>1</fileNumber>

    <objList>орг,1</objList>

    <docName>finDocument</docName>

    <version>15.0  Revision: b43d543f5e7f</version>

    <2109> rls   date: 18.08.03 18:20  </2019>

    <exportDate>01/03/2018</exportDate>

    <exportTime>11:36:49</exportTime>

    <baseNum>0</baseNum>

    <dateFrom>28/02/2018</dateFrom>

Как выйти из этой ситуации? Сам файла сваливается из другой системы. Мб как в 1С это дело обойти можно не правя каждый раз файл руками?

The document basically has «catalog» as the root tag with child tags of «movie» followed by one or more «actor». Each of these child tags further contains more child tags. I was supposed to make a DTD for this based on some rules given, but it is just rejecting whatever I put at the beginning of the doucment. Any help?

Here is the XML code:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<!DOCTYPE catalog SYSTEM "catalog.dtd">

<catalog>
    <movie movieID="m0100" genre="drama">
    <title>Monster&apos;s Ball</title>
<year>2001</year> 
<length>111 minutes</length>
<topBilledActors actorIDs="a0100 a0102" />
</movie>

<actor actorID="a0100" oscarWinner="yes">
    <name>Halle Berry</name>
<date>August 14, 1966</date>
<birthplace>Cleveland, Ohio</birthplace>
<role character="Leticia Musgrove" movie="m0100" />
<role character="Storm" movie="m0101" />
</actor>

<actor actorID="a0102" oscarWinner="yes">
    <name>Billy Bob Thornton</name>
<role character="Hank Grotowski" movie="m0100" />
</actor>

<movie movieID="m0101" genre="fantasy">
    <title>X-Men</title>
<year>2000</year>
<length>104 minutes</length>
<topBilledActors actorIDs="a0100 a0103" />
</movie>

<actor actorID="a0103" oscarWinner="no">
    <name>Ian McKellen</name>
<role character="Magneto" movie="m0101" />
<role character="Gandolf" movie="m0105" />
<role character="Gandolf" movie="m0107" />
</actor>

<movie movieID="m0105" genre="action" earningsRank="17">
    <name>Lord of the Rings: The Fellowship of the Ring</name>
<date>2001</date>
<length>178 minutes</length>
<topBilledActors actorIDs="a0103" />
</movie>

<movie movieID="m0107" genre="action" earningsRank="8">
    <name>Lord of the Rings: The Return of the King</name>
<date>2003</date>
<length>201 minutes</length>
<topBilledActors actorIDs="a0103" />
</movie>

<actor actorID="a0101" oscarWinner="yes">
<name>Tom Hanks</name>
<date>July 9, 1956</date>
<birthplace>Concord, California</birthplace>
<role character="Captain John H. Miller" movie="m0102" />
<role character="Forrest Gump" movie="m0103" />
<role character="Andrew Beckett" movie="m0104" />
</actor>

<movie movieID="m0102" genre="action" earningsRank="50">
    <name>Saving Private Ryan</name>
<date>1998</date>
<length>170 minutes</length>
<topBilledActors actorIDs="a0101 a0104" />
</movie>

<actor actorID="a0104" oscarWinner="yes">
    <name>Matt Damon</name>
<date>October 8, 1970</date>
<birthplace>Cambridge, Massachusetts</birthplace>
<role character="Private James Francis Ryan" movie="m0102" />
</actor>

<movie movieID="m0103" genre="comedy" earningsRank="14">
    <name>Forrest Gump</name>
<date>1994</date>
<length>142 minutes</length>
<topBilledActors actorIDs="a0101 a0105 a0106" />
</movie>

<actor actorID="a0105" oscarWinner="yes">
    <name>Sally Field</name>
<birthplace>Pasadena, California</birthplace>
<role character="Mrs. Gump" movie="m0103" />
</actor>

<actor actorID="a0106">
    <name>Gary Sinise</name>
<role character="Lt. Dan Taylor" movie="m0103" />
<role character="Ken Mattingly" movie="m0106" />
</actor>

<movie movieID="m0104" genre="drama">
    <name>Philadelphia</name>
<date>1993</date>
<length>125 minutes</length>
<topBilledActors actorIDs="a0101 a0107" />
</movie>

<movie movieID="m0106" genre="drama">
    <name>Apollo 13</name>
<date>1995</date>
<length>140 minutes</length>
<topBilledActors actorIDs="a0101 a0106" />
</movie>

<actor actorID="a0107" oscarWinner="yes">
    <name>Denzel Washington</name>
<role character="Joe Miller" movie="m0104" />
</actor>

</catalog>

Here is the DTD file:

<!ELEMENT catalog (movie, actor+)*>

<!ELEMENT movie (title, year, length, topBilledActors)>
<!ATTLIST movie movieID ID #REQUIRED>
<!ATTLIST movie genre (fantasy |  action | drama | comedy) #REQUIRED>
<!ATTLIST movie earningsRank CDATA #IMPLIED>

<!ELEMENT title (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT length (#PCDATA)>
<!ELEMENT topBilledActors EMPTY>
<!ATTLIST topBilledActors ActorIDs IDREFS>

<!ELEMENT actor (name, date*, birthplace*, role+)>
<!ATTLIST actor actorID ID #REQUIRED>
<!ATTLIST actor oscarWinner (yes|no) "no">

<!ELEMENT name (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT birthplace (#PCDATA)>
<!ELEMENT role EMPTY>
<!ATTLIST role character CDATA>
<!ATTLIST role movie IDREF>

EDIT: I am verifying this with the XML validator at http://www.w3schools.com/xml/xml_validator.asp

My web browser (IE) does not display the file and gives the error:

Required white space was missing. Error processing resource 'file:///C:/Documents and        Settings/Administrator/Desktop/...

 <!ATTLIST topBilledActors ActorIDs IDREFS>

Содержание:

1.       XML – расширяемый язык разметки

2.       Устранение Ошибки разбора XML в 1С

3.       «Обход» Ошибки разбора XML в 1С   

1.    XML – расширяемый язык разметки

В данной статье речь пойдёт о причинах возникновения фатальной ошибки «Ошибка разбора XML» и способах устранения данной неполадки. Также будет дана инструкция не по устранению, но «обходу» ошибки, то есть действиям на опережение.

XML (с английского – extensible markup language – расширяемый язык разметки) – это язык разметки, который рекомендует Консорциум Всемирной паутины. Обычно язык разметки XML служит для описания документации, соответствующего типа, а также описывает действия соответствующих процессоров. Расширяемый язык разметки имеет довольно простой синтаксис, поэтому используется по всему миру, чтобы создавать и обрабатывать документацию программным способом. Он создавался именно для использования в Интернете. XML назвали именно расширяемым языком разметки, так как в нём нет фиксации разметки, которая содержится внутри документа, а именно: программист может создавать любую разметку, а ограничения будут встречаться лишь в синтаксисе.

2.    Устранение Ошибки разбора XML в 1С

«Ошибка разбора XML» возникает исключительно в тонком клиенте 1С. Также стоит отметить, что «Ошибка разбора XML» также довольна схожа с ошибкой по формату потока, которая возникает в толстом клиенте. Обычно в 1С «Ошибка разбора XML» возникает по причине наличия кэша метаданных. И если очистить кэш, то ошибка будет устранена. Выглядит окно с ошибкой, а также окно с комментариями от технической поддержки следующим образом:

Рис. 1 Окно Ошибки разбора XML в 1С

XML данные читаются по потокам, так что в каждый из моментов времени объект «сосредоточен» в некотором узле XML. Из-за этого также может возникать фатальная ошибка «Ошибка разбора XML». Для того чтобы её устранить, можно вызвать функцию «ИсключениеЧтенияXml», как показано на скриншоте примера ниже:

Рис. 2 Вызов функции ИсключениеЧтенияXML для устранения Ошибки разбора XML в 1С  

3.    «Обход» Ошибки разбора XML в 1С

Данные два способа (очистка кэша метаданных и функция «ИсключениеЧтенияXml») – не все возможные варианты устранения ошибки разбора XML. Далее рассмотрим нестандартный подход, который позволит избежать ошибки еще до её возникновения.

Для наглядности будем работать в конфигурации 1С:Бухгалтерия предприятия, одной из наиболее распространенных программ фирмы 1С. У многих людей, которые пользуются программой 1С:Отчётность появляются неполадки при попытках открыть данные/файлы от налоговой. Чтобы открыть такой файл повторяем следующие действия:

·        Переходим по пути: «Настройки 1С:Отчётности → Журнал обмена с контролирующими органами», как показано на скриншоте ниже:

Рис. 3 Настройка 1С Отчетности

·        Далее кликаем на «Запросы» и выделяем ту выписку, которую не было возможности открыть из-за ошибки, как продемонстрировано на скриншоте ниже:

Рис. 4 Выбор выписки с Ошибкой разбора XML в 1С

·        Обращаем внимание на стадию отправки, которая располагается внизу этого сообщения, и кликаем два раза на зелёный круг:

Рис. 5 Стадия отправки документа с Ошибкой разбора XML в 1С

·      Появляется транспортное сообщение, в нём кликаем на «Выгрузить» и выбираем папку, куда необходимо провести выгрузку, после чего сохраняем данный файл. Пробуем открыть его, при помощи любого из графических редакторов, который может поддерживать формат PDF, как показано на скриншоте ниже:

Рис. 6 Результат обхода Ошибки разбора XML в 1С

·        Всё успешно открылось, а ошибка даже не успела возникнуть.

Специалист компании «Кодерлайн»

Айдар Фархутдинов

The document basically has «catalog» as the root tag with child tags of «movie» followed by one or more «actor». Each of these child tags further contains more child tags. I was supposed to make a DTD for this based on some rules given, but it is just rejecting whatever I put at the beginning of the doucment. Any help?

Here is the XML code:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<!DOCTYPE catalog SYSTEM "catalog.dtd">

<catalog>
    <movie movieID="m0100" genre="drama">
    <title>Monster&apos;s Ball</title>
<year>2001</year> 
<length>111 minutes</length>
<topBilledActors actorIDs="a0100 a0102" />
</movie>

<actor actorID="a0100" oscarWinner="yes">
    <name>Halle Berry</name>
<date>August 14, 1966</date>
<birthplace>Cleveland, Ohio</birthplace>
<role character="Leticia Musgrove" movie="m0100" />
<role character="Storm" movie="m0101" />
</actor>

<actor actorID="a0102" oscarWinner="yes">
    <name>Billy Bob Thornton</name>
<role character="Hank Grotowski" movie="m0100" />
</actor>

<movie movieID="m0101" genre="fantasy">
    <title>X-Men</title>
<year>2000</year>
<length>104 minutes</length>
<topBilledActors actorIDs="a0100 a0103" />
</movie>

<actor actorID="a0103" oscarWinner="no">
    <name>Ian McKellen</name>
<role character="Magneto" movie="m0101" />
<role character="Gandolf" movie="m0105" />
<role character="Gandolf" movie="m0107" />
</actor>

<movie movieID="m0105" genre="action" earningsRank="17">
    <name>Lord of the Rings: The Fellowship of the Ring</name>
<date>2001</date>
<length>178 minutes</length>
<topBilledActors actorIDs="a0103" />
</movie>

<movie movieID="m0107" genre="action" earningsRank="8">
    <name>Lord of the Rings: The Return of the King</name>
<date>2003</date>
<length>201 minutes</length>
<topBilledActors actorIDs="a0103" />
</movie>

<actor actorID="a0101" oscarWinner="yes">
<name>Tom Hanks</name>
<date>July 9, 1956</date>
<birthplace>Concord, California</birthplace>
<role character="Captain John H. Miller" movie="m0102" />
<role character="Forrest Gump" movie="m0103" />
<role character="Andrew Beckett" movie="m0104" />
</actor>

<movie movieID="m0102" genre="action" earningsRank="50">
    <name>Saving Private Ryan</name>
<date>1998</date>
<length>170 minutes</length>
<topBilledActors actorIDs="a0101 a0104" />
</movie>

<actor actorID="a0104" oscarWinner="yes">
    <name>Matt Damon</name>
<date>October 8, 1970</date>
<birthplace>Cambridge, Massachusetts</birthplace>
<role character="Private James Francis Ryan" movie="m0102" />
</actor>

<movie movieID="m0103" genre="comedy" earningsRank="14">
    <name>Forrest Gump</name>
<date>1994</date>
<length>142 minutes</length>
<topBilledActors actorIDs="a0101 a0105 a0106" />
</movie>

<actor actorID="a0105" oscarWinner="yes">
    <name>Sally Field</name>
<birthplace>Pasadena, California</birthplace>
<role character="Mrs. Gump" movie="m0103" />
</actor>

<actor actorID="a0106">
    <name>Gary Sinise</name>
<role character="Lt. Dan Taylor" movie="m0103" />
<role character="Ken Mattingly" movie="m0106" />
</actor>

<movie movieID="m0104" genre="drama">
    <name>Philadelphia</name>
<date>1993</date>
<length>125 minutes</length>
<topBilledActors actorIDs="a0101 a0107" />
</movie>

<movie movieID="m0106" genre="drama">
    <name>Apollo 13</name>
<date>1995</date>
<length>140 minutes</length>
<topBilledActors actorIDs="a0101 a0106" />
</movie>

<actor actorID="a0107" oscarWinner="yes">
    <name>Denzel Washington</name>
<role character="Joe Miller" movie="m0104" />
</actor>

</catalog>

Here is the DTD file:

<!ELEMENT catalog (movie, actor+)*>

<!ELEMENT movie (title, year, length, topBilledActors)>
<!ATTLIST movie movieID ID #REQUIRED>
<!ATTLIST movie genre (fantasy |  action | drama | comedy) #REQUIRED>
<!ATTLIST movie earningsRank CDATA #IMPLIED>

<!ELEMENT title (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT length (#PCDATA)>
<!ELEMENT topBilledActors EMPTY>
<!ATTLIST topBilledActors ActorIDs IDREFS>

<!ELEMENT actor (name, date*, birthplace*, role+)>
<!ATTLIST actor actorID ID #REQUIRED>
<!ATTLIST actor oscarWinner (yes|no) "no">

<!ELEMENT name (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT birthplace (#PCDATA)>
<!ELEMENT role EMPTY>
<!ATTLIST role character CDATA>
<!ATTLIST role movie IDREF>

EDIT: I am verifying this with the XML validator at http://www.w3schools.com/xml/xml_validator.asp

My web browser (IE) does not display the file and gives the error:

Required white space was missing. Error processing resource 'file:///C:/Documents and        Settings/Administrator/Desktop/...

 <!ATTLIST topBilledActors ActorIDs IDREFS>

@c-x,

Looking at what you’ve described so far, I’m having a bit of trouble figuring out how callTaxiiService2 would be where the code is failing.

First, you mention StartTag: invalid element name, line 555, column 2, which has a few hints:

  • The invalid element name is an XML parse error, and the code you show does not attempt to parse XML until the line that reads taxii_message = t.get_message_from_http_response(resp, poll_req.message_id)
  • The error location is line 555, column 2, which seems to indicate that the error is in a Poll Response. TAXII Poll Requests like the one the above code creates are only a few lines (maybe 10-15 if you pretty print it). If the error is in fact in a Poll Response, that means you are getting a response from the server.

Second, you mention that the error occurs when libtaxii is processing an addinfourl object. addinfourl objects are returned by callTaxiiService2 (specifically libtaxii’s underlying use of urllib2.urlopen), which leads me to think that the callTaxiiService2 returned successfully. If that function failed, I do not have an explanation as to how you’d have a handle on the return object.

The t.get_message_from_http_response(resp, poll_req.message_id) line parses XML from the HTTP Response (encapsulated in an addinfourl object) [1] [2].

I can replicate the error you are getting with the following code (note the extraneous begin bracket <):

from lxml import etree
etree.XML('<hello><</hello>')
# Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#  File "lxml.etree.pyx", line 3072, in lxml.etree.XML (srclxmllxml.etree.c:70460)
#  File "parser.pxi", line 1828, in lxml.etree._parseMemoryDocument (srclxmllxml.etree.c:106689)
#  File "parser.pxi", line 1716, in lxml.etree._parseDoc (srclxmllxml.etree.c:105478)
#  File "parser.pxi", line 1086, in lxml.etree._BaseParser._parseDoc (srclxmllxml.etree.c:100105)
#  File "parser.pxi", line 580, in lxml.etree._ParserContext._handleParseResultDoc (srclxmllxml.etree.c:94543)
#  File "parser.pxi", line 690, in lxml.etree._handleParseResult (srclxmllxml.etree.c:96003)
#  File "parser.pxi", line 620, in lxml.etree._raiseParseError (srclxmllxml.etree.c:95050)
# lxml.etree.XMLSyntaxError: StartTag: invalid element name, line 1, column 9

Based on that, my bet is that the STIX content in the Poll Response has an extra begin bracket (therefore being invalid XML) and that’s what’s blowing up.

As @gtback mentioned to me offline, libtaxii can do a much better job of handling processing errors. So regardless of this issue’s resolution, I’ll open an issue for that.

@c-x — I don’t mean to disagree too much, but I’m having trouble arriving at your conclusion with the evidence you’ve provided. I’ve attempted to explain my thought process so that we can reach a conclusion about what’s happening and the best way to fix it. I realize I’m not coming from the debug logs (like you are), but rather an understanding of the code, so I may be missing a key piece of information.

Thank you.
-Mark

[1] https://github.com/TAXIIProject/libtaxii/blob/master/libtaxii/__init__.py#L96
[2] https://github.com/TAXIIProject/libtaxii/blob/master/libtaxii/messages_11.py#L87

I have a Ruby script which does a query to a .NET ASP server and gets the result as a string of XML;

<?xml version="1.0" encoding="utf-8"?>
<Envelope>
  <Body>
    <QueryServicesResponse>
      <QueryServicesResult>
        <Date>2016-01-01</Date>
        <serviceList>
          <service>
            <uuid>10264b70-87ee-11e6-ae22-56b6b6499611</uuid>
            <flight>EZY0000</flight>
            <originName>London Heathrow</originName>
            <originShort>LHR</originShort>
            <destinationName>London Stansted</destinationName>
            <destinationShort>STN</destinationShort>
            <scheduledDeparture>2016-01-01T14:00:00</scheduledDeparture>
            <scheduledArrival>2016-01-01T14:30:00</scheduledArrival>
          </service>
        </serviceList>
      </QueryServicesResult>
    </QueryServicesResponse>
  </Body>
</Envelope>

This is the section of the ruby scrip which deals with the returned body;

# Post the request
resp, data = http.post(path, data, headers)

# Output the results
doc = Nokogiri::XML(resp.body)
doc.remove_namespaces!
puts doc

The ruby script is called via a php file with the following code;

<?php
$xml = exec("ruby test.rb EZY0000",($results));

$xmlparse = simplexml_load_string($xml);
    echo $xmlparse;
?>

But php Throws the following errors when trying to parse the result;

PHP Warning: simplexml_load_string(): Entity: line 1: parser error :
StartTag: invalid element name

PHP Warning: simplexml_load_string(): &lt;/Envelope&gt;

I’m trying to parse the xml into a SimpleXMLElement Object I’ve been trying all sorts of things over the past few days but am stuck or blind to the problem now. I’ve tried htmlspecialchars but that didn’t help either.

The only thing I can think of is this has something to do with the string coming from the ruby script even though it appears to be, and validates as proper xml.

If I take the xml above and use the following php code then everything works as expected and I get the desired result;

<?php
$string = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<Envelope>
  <Body>
    <QueryServicesResponse>
      <QueryServicesResult>
        <Date>2016-01-01</Date>
        <serviceList>
          <service>
            <uuid>10264b70-87ee-11e6-ae22-56b6b6499611</uuid>
            <flight>EZY0000</flight>
            <originName>London Heathrow</originName>
            <originShort>LHR</originShort>
            <destinationName>London Stansted</destinationName>
            <destinationShort>STN</destinationShort>
            <scheduledDeparture>2016-01-01T14:00:00</scheduledDeparture>
            <scheduledArrival>2016-01-01T14:30:00</scheduledArrival>
          </service>
        </serviceList>
      </QueryServicesResult>
    </QueryServicesResponse>
  </Body>
</Envelope>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

Which gives me;

SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
            [QueryServicesResponse] => SimpleXMLElement Object
                (
                    [QueryServicesResult] => SimpleXMLElement Object
                        (
                            [Date] => 2016-01-01
                            [serviceList] => SimpleXMLElement Object
                                (
                                    [service] => SimpleXMLElement Object
                                        (
                                            [uuid] => 10264b70-87ee-11e6-ae22-56b6b6499611
                                            [flight] => EZY0000
                                            [originName] => London Heathrow
                                            [originShort] => LHR
                                            [destinationName] => London Stansted
                                            [destinationShort] => STN
                                            [scheduledDeparture] => 2016-01-01T14:00:00
                                            [scheduledArrival] => 2016-01-01T14:30:00
                                        )
                                )
                        )
                )
        )
)

So how can I get the xml from my ruby script into a valid object which I can manipulate in php? Someome offline said I should try and do it all in Rails — but I’m not ready for anything like that much of a challenge at the moment.

I have a Ruby script which does a query to a .NET ASP server and gets the result as a string of XML;

<?xml version="1.0" encoding="utf-8"?>
<Envelope>
  <Body>
    <QueryServicesResponse>
      <QueryServicesResult>
        <Date>2016-01-01</Date>
        <serviceList>
          <service>
            <uuid>10264b70-87ee-11e6-ae22-56b6b6499611</uuid>
            <flight>EZY0000</flight>
            <originName>London Heathrow</originName>
            <originShort>LHR</originShort>
            <destinationName>London Stansted</destinationName>
            <destinationShort>STN</destinationShort>
            <scheduledDeparture>2016-01-01T14:00:00</scheduledDeparture>
            <scheduledArrival>2016-01-01T14:30:00</scheduledArrival>
          </service>
        </serviceList>
      </QueryServicesResult>
    </QueryServicesResponse>
  </Body>
</Envelope>

This is the section of the ruby scrip which deals with the returned body;

# Post the request
resp, data = http.post(path, data, headers)

# Output the results
doc = Nokogiri::XML(resp.body)
doc.remove_namespaces!
puts doc

The ruby script is called via a php file with the following code;

<?php
$xml = exec("ruby test.rb EZY0000",($results));

$xmlparse = simplexml_load_string($xml);
    echo $xmlparse;
?>

But php Throws the following errors when trying to parse the result;

PHP Warning: simplexml_load_string(): Entity: line 1: parser error :
StartTag: invalid element name

PHP Warning: simplexml_load_string(): &lt;/Envelope&gt;

I’m trying to parse the xml into a SimpleXMLElement Object I’ve been trying all sorts of things over the past few days but am stuck or blind to the problem now. I’ve tried htmlspecialchars but that didn’t help either.

The only thing I can think of is this has something to do with the string coming from the ruby script even though it appears to be, and validates as proper xml.

If I take the xml above and use the following php code then everything works as expected and I get the desired result;

<?php
$string = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<Envelope>
  <Body>
    <QueryServicesResponse>
      <QueryServicesResult>
        <Date>2016-01-01</Date>
        <serviceList>
          <service>
            <uuid>10264b70-87ee-11e6-ae22-56b6b6499611</uuid>
            <flight>EZY0000</flight>
            <originName>London Heathrow</originName>
            <originShort>LHR</originShort>
            <destinationName>London Stansted</destinationName>
            <destinationShort>STN</destinationShort>
            <scheduledDeparture>2016-01-01T14:00:00</scheduledDeparture>
            <scheduledArrival>2016-01-01T14:30:00</scheduledArrival>
          </service>
        </serviceList>
      </QueryServicesResult>
    </QueryServicesResponse>
  </Body>
</Envelope>
XML;

$xml = simplexml_load_string($string);

print_r($xml);
?>

Which gives me;

SimpleXMLElement Object
(
    [Body] => SimpleXMLElement Object
        (
            [QueryServicesResponse] => SimpleXMLElement Object
                (
                    [QueryServicesResult] => SimpleXMLElement Object
                        (
                            [Date] => 2016-01-01
                            [serviceList] => SimpleXMLElement Object
                                (
                                    [service] => SimpleXMLElement Object
                                        (
                                            [uuid] => 10264b70-87ee-11e6-ae22-56b6b6499611
                                            [flight] => EZY0000
                                            [originName] => London Heathrow
                                            [originShort] => LHR
                                            [destinationName] => London Stansted
                                            [destinationShort] => STN
                                            [scheduledDeparture] => 2016-01-01T14:00:00
                                            [scheduledArrival] => 2016-01-01T14:30:00
                                        )
                                )
                        )
                )
        )
)

So how can I get the xml from my ruby script into a valid object which I can manipulate in php? Someome offline said I should try and do it all in Rails — but I’m not ready for anything like that much of a challenge at the moment.

(Предупреждение — новичок asp) У меня есть файл aspx с тегом

    <%@ Page Language=VB  ... %>

В самом начале файла.

При вызове этого с моего сервера IIS (http: //localhost/myservice/default.aspx) это дает мне ошибку

This page contains the following
errors:

error on line 1 at column 2:
StartTag: invalid element name
Below is a rendering of the page up to
the first error.

Что я делаю не так?

Перейти к ответу
Данный вопрос помечен как решенный


Ответы
7

Создается впечатление, что браузер пытается отобразить то, что, по его мнению, является файлом XML, поскольку выдает ошибку на втором символе первой строки. Поэтому я думаю, что файл не анализируется, а просто немедленно возвращается как есть. Убедитесь, что ваш сервер IIS настроен правильно и действительно ли он анализирует ваши теги ASP перед возвратом страницы.

Когда я перешел на вкладку ASP.NET для виртуального каталога, я заметил, что версия ASP.NET не была выбрана (это было пустое поле со списком). Выбор версии .NET framework сделал свое дело. Спасибо.

Как и в предыдущем комментарии, в моей настройке тоже не была выбрана версия ASP.NET. Но после выбора версии я получил следующую ошибку при доступе к файлу aspx.
Windows XP, IIS 5.1.
Сведения об исключении: System.Web.Hosting.HostingEnvironmentException: не удалось получить доступ к метабазе IIS.

Выполнил следующие команды, aspnet_iis -i
и aspnet_iis -ga

Решил проблему.

Когда я это сделал. Работало нормально.

Перейдите в эту директорию в командной строке C: WINDOWS Microsoft.NET Framework v2.0.50727
Запустите эту команду
Aspnet_regiis -I

Это установит aspnet

Попробуй это :

Чтобы установить и включить ASP.NET:

Щелкните Пуск, а затем щелкните Панель управления.
Щелкните «Установка и удаление программ».
Щелкните Добавить / удалить компоненты Windows.
Дважды щелкните Сервер приложений, а затем щелкните Подробности.
Установите флажок ASP.NET и нажмите кнопку ОК.
Нажмите «Далее.
Щелкните Готово.

Для меня проблема заключалась в том, что я просматривал файл .svc, используя свой локальный путь к файлу, сопоставленный с сервером в моем браузере, когда я хотел использовать дословный путь к моему серверу.

Для меня проблема заключалась в сериализации, которая отвечала клиенту.

Моя проблема заключалась в пространствах тегов xml:

  - < tag > text < / tag >  ---> wrong

  - <tag> text </tag> ----> good.

Другие вопросы по теме

The document basically has «catalog» as the root tag with child tags of «movie» followed by one or more «actor». Each of these child tags further contains more child tags. I was supposed to make a DTD for this based on some rules given, but it is just rejecting whatever I put at the beginning of the doucment. Any help?

Here is the XML code:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

<!DOCTYPE catalog SYSTEM "catalog.dtd">

<catalog>
    <movie movieID="m0100" genre="drama">
    <title>Monster&apos;s Ball</title>
<year>2001</year> 
<length>111 minutes</length>
<topBilledActors actorIDs="a0100 a0102" />
</movie>

<actor actorID="a0100" oscarWinner="yes">
    <name>Halle Berry</name>
<date>August 14, 1966</date>
<birthplace>Cleveland, Ohio</birthplace>
<role character="Leticia Musgrove" movie="m0100" />
<role character="Storm" movie="m0101" />
</actor>

<actor actorID="a0102" oscarWinner="yes">
    <name>Billy Bob Thornton</name>
<role character="Hank Grotowski" movie="m0100" />
</actor>

<movie movieID="m0101" genre="fantasy">
    <title>X-Men</title>
<year>2000</year>
<length>104 minutes</length>
<topBilledActors actorIDs="a0100 a0103" />
</movie>

<actor actorID="a0103" oscarWinner="no">
    <name>Ian McKellen</name>
<role character="Magneto" movie="m0101" />
<role character="Gandolf" movie="m0105" />
<role character="Gandolf" movie="m0107" />
</actor>

<movie movieID="m0105" genre="action" earningsRank="17">
    <name>Lord of the Rings: The Fellowship of the Ring</name>
<date>2001</date>
<length>178 minutes</length>
<topBilledActors actorIDs="a0103" />
</movie>

<movie movieID="m0107" genre="action" earningsRank="8">
    <name>Lord of the Rings: The Return of the King</name>
<date>2003</date>
<length>201 minutes</length>
<topBilledActors actorIDs="a0103" />
</movie>

<actor actorID="a0101" oscarWinner="yes">
<name>Tom Hanks</name>
<date>July 9, 1956</date>
<birthplace>Concord, California</birthplace>
<role character="Captain John H. Miller" movie="m0102" />
<role character="Forrest Gump" movie="m0103" />
<role character="Andrew Beckett" movie="m0104" />
</actor>

<movie movieID="m0102" genre="action" earningsRank="50">
    <name>Saving Private Ryan</name>
<date>1998</date>
<length>170 minutes</length>
<topBilledActors actorIDs="a0101 a0104" />
</movie>

<actor actorID="a0104" oscarWinner="yes">
    <name>Matt Damon</name>
<date>October 8, 1970</date>
<birthplace>Cambridge, Massachusetts</birthplace>
<role character="Private James Francis Ryan" movie="m0102" />
</actor>

<movie movieID="m0103" genre="comedy" earningsRank="14">
    <name>Forrest Gump</name>
<date>1994</date>
<length>142 minutes</length>
<topBilledActors actorIDs="a0101 a0105 a0106" />
</movie>

<actor actorID="a0105" oscarWinner="yes">
    <name>Sally Field</name>
<birthplace>Pasadena, California</birthplace>
<role character="Mrs. Gump" movie="m0103" />
</actor>

<actor actorID="a0106">
    <name>Gary Sinise</name>
<role character="Lt. Dan Taylor" movie="m0103" />
<role character="Ken Mattingly" movie="m0106" />
</actor>

<movie movieID="m0104" genre="drama">
    <name>Philadelphia</name>
<date>1993</date>
<length>125 minutes</length>
<topBilledActors actorIDs="a0101 a0107" />
</movie>

<movie movieID="m0106" genre="drama">
    <name>Apollo 13</name>
<date>1995</date>
<length>140 minutes</length>
<topBilledActors actorIDs="a0101 a0106" />
</movie>

<actor actorID="a0107" oscarWinner="yes">
    <name>Denzel Washington</name>
<role character="Joe Miller" movie="m0104" />
</actor>

</catalog>

Here is the DTD file:

<!ELEMENT catalog (movie, actor+)*>

<!ELEMENT movie (title, year, length, topBilledActors)>
<!ATTLIST movie movieID ID #REQUIRED>
<!ATTLIST movie genre (fantasy |  action | drama | comedy) #REQUIRED>
<!ATTLIST movie earningsRank CDATA #IMPLIED>

<!ELEMENT title (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT length (#PCDATA)>
<!ELEMENT topBilledActors EMPTY>
<!ATTLIST topBilledActors ActorIDs IDREFS>

<!ELEMENT actor (name, date*, birthplace*, role+)>
<!ATTLIST actor actorID ID #REQUIRED>
<!ATTLIST actor oscarWinner (yes|no) "no">

<!ELEMENT name (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT birthplace (#PCDATA)>
<!ELEMENT role EMPTY>
<!ATTLIST role character CDATA>
<!ATTLIST role movie IDREF>

EDIT: I am verifying this with the XML validator at http://www.w3schools.com/xml/xml_validator.asp

My web browser (IE) does not display the file and gives the error:

Required white space was missing. Error processing resource 'file:///C:/Documents and        Settings/Administrator/Desktop/...

 <!ATTLIST topBilledActors ActorIDs IDREFS>

У меня есть серьезная проблема с получением данных из SQL-запроса в php в xml. Я всегда получаю ошибку: StartTag: invalid element name. The Start-Element is a Number, я не знаю, если это имеет значение?!?

Возможно, вы, ребята, можете мне помочь!!

PHP:

$query = "SELECT r.object_id,
t.term_taxonomy_id,
t.term_id,
t.taxonomy,
t.description,
p.post_date_gmt,
p.post_content,
p.post_title,
p.post_excerpt 
FROM wp_posts p,
wp_term_taxonomy t,
wp_term_relationships r
WHERE r.object_id= p.id
AND t.term_taxonomy_id = r.term_taxonomy_id
AND p.post_status = 'publish'
AND p.post_type = 'post'
AND to_days(p.post_date_gmt) >= to_days(now()) - 120
ORDER BY p.post_date DESC";


// DB Connect

$connection = mysql_connect($server, $user, $password);
mysql_select_db($dbName, $connection);
$res = mysql_query($query);

// XML Output

$xml = '<?xml version="1.0" encoding="UTF-8"?>
<standing version="1.0">';
while ($row = mysql_fetch_assoc($res)){
    $xml .= '
    <'.$row['object_id'].'>
      <term_taxonomy>'.$row['taxonomy'].'</term_taxonomy>
      <description>'.$row['description'].'</description>
      <post_date>'.$row['post_date_gmt'].'</post_date>
      <post_content>'.$row['post_content'].'</post_content>
      <post_title>'.$row['post_title'].'</pst_title>
      <post_exerpt>'.$row['post_exerpt'].'</post_exerpt>
    </'.$row['object_id'].'>
    ';
}
$xml.= '</standing>';


// Write to file

$file = 'News.xml'; 
if(is_file($file)) unlink($file);
$fp = fopen($file, "w+");
fwrite($fp, $xml);
fclose($fp);
mysql_close ($connection);
?>

Продолжение истории:

Заходим в папку с плагином и в файле shopYandexmarketPluginRun.controller.php меняем первую строку на строку отсюда <?xml version=»1.0″ encoding=»windows-1251″?>. В этой строке подставляем кодировку с {$this->encoding} вместо windows-1251.

Проверяем загрузку прайса по ссылке:

и опять получаем ту-же ошибку:

Но вот в чем загвоздка, проверяем загрузку этого же файла скаченного на компьютер:


и вуаля:


Все подгружается без проблем.

В чем трабл-кто нибудь подскажет?

Привет форумчане!Пытаюсь загрузить данные из XML в 1С. Вылетает с такой ошибкой:

Ошибка при вызове метода контекста (Прочитать)

                    Пока Файл.Прочитать() Цикл

по причине:

Ошибка разбора XML:  — [9,6]

Фатальная ошибка:

StartTag: invalid element name

В самом файле XML как раз на цифровой тег ругается, руками если поправить на любое другое имя не числовое, грузит нормально тогда.

<?xml version=’1.0′ encoding=’windows-1251′?>

<root>

<header>

    <fileName>тут был путь к файлу</fileName>

    <fileNumber>1</fileNumber>

    <objList>орг,1</objList>

    <docName>finDocument</docName>

    <version>15.0  Revision: b43d543f5e7f</version>

    <2109> rls   date: 18.08.03 18:20  </2019>

    <exportDate>01/03/2018</exportDate>

    <exportTime>11:36:49</exportTime>

    <baseNum>0</baseNum>

    <dateFrom>28/02/2018</dateFrom>

Как выйти из этой ситуации? Сам файла сваливается из другой системы. Мб как в 1С это дело обойти можно не правя каждый раз файл руками?

@c-x,

Looking at what you’ve described so far, I’m having a bit of trouble figuring out how callTaxiiService2 would be where the code is failing.

First, you mention StartTag: invalid element name, line 555, column 2, which has a few hints:

  • The invalid element name is an XML parse error, and the code you show does not attempt to parse XML until the line that reads taxii_message = t.get_message_from_http_response(resp, poll_req.message_id)
  • The error location is line 555, column 2, which seems to indicate that the error is in a Poll Response. TAXII Poll Requests like the one the above code creates are only a few lines (maybe 10-15 if you pretty print it). If the error is in fact in a Poll Response, that means you are getting a response from the server.

Second, you mention that the error occurs when libtaxii is processing an addinfourl object. addinfourl objects are returned by callTaxiiService2 (specifically libtaxii’s underlying use of urllib2.urlopen), which leads me to think that the callTaxiiService2 returned successfully. If that function failed, I do not have an explanation as to how you’d have a handle on the return object.

The t.get_message_from_http_response(resp, poll_req.message_id) line parses XML from the HTTP Response (encapsulated in an addinfourl object) [1] [2].

I can replicate the error you are getting with the following code (note the extraneous begin bracket <):

from lxml import etree
etree.XML('<hello><</hello>')
# Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#  File "lxml.etree.pyx", line 3072, in lxml.etree.XML (srclxmllxml.etree.c:70460)
#  File "parser.pxi", line 1828, in lxml.etree._parseMemoryDocument (srclxmllxml.etree.c:106689)
#  File "parser.pxi", line 1716, in lxml.etree._parseDoc (srclxmllxml.etree.c:105478)
#  File "parser.pxi", line 1086, in lxml.etree._BaseParser._parseDoc (srclxmllxml.etree.c:100105)
#  File "parser.pxi", line 580, in lxml.etree._ParserContext._handleParseResultDoc (srclxmllxml.etree.c:94543)
#  File "parser.pxi", line 690, in lxml.etree._handleParseResult (srclxmllxml.etree.c:96003)
#  File "parser.pxi", line 620, in lxml.etree._raiseParseError (srclxmllxml.etree.c:95050)
# lxml.etree.XMLSyntaxError: StartTag: invalid element name, line 1, column 9

Based on that, my bet is that the STIX content in the Poll Response has an extra begin bracket (therefore being invalid XML) and that’s what’s blowing up.

As @gtback mentioned to me offline, libtaxii can do a much better job of handling processing errors. So regardless of this issue’s resolution, I’ll open an issue for that.

@c-x — I don’t mean to disagree too much, but I’m having trouble arriving at your conclusion with the evidence you’ve provided. I’ve attempted to explain my thought process so that we can reach a conclusion about what’s happening and the best way to fix it. I realize I’m not coming from the debug logs (like you are), but rather an understanding of the code, so I may be missing a key piece of information.

Thank you.
-Mark

[1] https://github.com/TAXIIProject/libtaxii/blob/master/libtaxii/__init__.py#L96
[2] https://github.com/TAXIIProject/libtaxii/blob/master/libtaxii/messages_11.py#L87

So you’ve enabled your Magento cache and your var/log/system.log file is starting to fill up with entries. This is because it’s just built a cache of your config.xml, system.xml & adminhtml.xml files and there is an error in one of them.

StartTag: invalid element name — This is often simple because the xml element starts with a number, but could be a symbol etc

Can we be sure it’s a configuration .xml file? Yep, because of the following error lib/Varien/Simplexml/Config.php

Navigate via SSH to your app directory and run

find . -type f -name «*.xml» -exec xmllint —noout {} ;

This will validate your xml files and find the bad one… hopefully.

Unfortunately Magento throws a spanner into the works that you should also be aware of  the table CORE_CONFIG_DATA in your database. Magento takes the path value of each entry and converts it to an XML. So in your core_config_data table, you may see postcode/license and Magento will convert this to <postcode><license>

However if an old module corrupted or was badly formed when it was saved, you may find something with a path like 2DSoR0swfgww77YzlyE0EsGDiyjUIE4G, which would create an XML value of <2DSoR0swfgww77YzlyE0EsGDiyjUIE4G>, which is invalid anyway but also doesn’t pertain to a modules configuration.

Delete this entry from your core_config_data table and you will be steam rolling along again

У меня есть серьезная проблема с получением данных из SQL-запроса в php в xml. Я всегда получаю ошибку: StartTag: invalid element name. The Start-Element is a Number, я не знаю, если это имеет значение?!?

Возможно, вы, ребята, можете мне помочь!!

PHP:

$query = "SELECT r.object_id,
t.term_taxonomy_id,
t.term_id,
t.taxonomy,
t.description,
p.post_date_gmt,
p.post_content,
p.post_title,
p.post_excerpt 
FROM wp_posts p,
wp_term_taxonomy t,
wp_term_relationships r
WHERE r.object_id= p.id
AND t.term_taxonomy_id = r.term_taxonomy_id
AND p.post_status = 'publish'
AND p.post_type = 'post'
AND to_days(p.post_date_gmt) >= to_days(now()) - 120
ORDER BY p.post_date DESC";


// DB Connect

$connection = mysql_connect($server, $user, $password);
mysql_select_db($dbName, $connection);
$res = mysql_query($query);

// XML Output

$xml = '<?xml version="1.0" encoding="UTF-8"?>
<standing version="1.0">';
while ($row = mysql_fetch_assoc($res)){
    $xml .= '
    <'.$row['object_id'].'>
      <term_taxonomy>'.$row['taxonomy'].'</term_taxonomy>
      <description>'.$row['description'].'</description>
      <post_date>'.$row['post_date_gmt'].'</post_date>
      <post_content>'.$row['post_content'].'</post_content>
      <post_title>'.$row['post_title'].'</pst_title>
      <post_exerpt>'.$row['post_exerpt'].'</post_exerpt>
    </'.$row['object_id'].'>
    ';
}
$xml.= '</standing>';


// Write to file

$file = 'News.xml'; 
if(is_file($file)) unlink($file);
$fp = fopen($file, "w+");
fwrite($fp, $xml);
fclose($fp);
mysql_close ($connection);
?>

 

Пользователь 250059

Заглянувший

Сообщений: 20
Баллов: 1
Регистрация: 26.03.2014

#1

0

06.02.2015 16:52:43

Добрый день, у меня на сайте есть структура разделов, я хочу перенести её в дерево групп 1С
В 1С есть возможность импорта дерева групп из XML но в битриксе при экспорте формируется огромный XML файл 18мб. разумеется 1С не понимает как с ним быть и выдает ошибку.

Код
{ПланОбмена.Б_ОбменССайтом.Форма.НастройкаДереваГрупп.Форма(469)}: Ошибка при вызове метода контекста (Прочитать): Ошибка разбора XML:  - [2,2]
Фатальная ошибка: 
StartTag: invalid element name

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

 

А вы это пытаетесь сделать не через помощник импорта каталога из Битрикс в 1С? Попробуйте сделать через Помощник. Там группы загружаются в начале, а товары можно и не загружать, если они там вместе с группами вам не нужны.

 

Нет хотелось по другому.
Объясняю.
Есть 1с и интернет-магазин в настоящий момент работал стандартный обмен данных с веб-сайтом.

http://prntscr.com/62x6aa

Структура на сайте и в 1с отличаются.
На этой недели установили дополнение 1с для обмена. Необходимо сохранить структуру созданную на сайте и импортировать её в модуль обмена 1с

http://prntscr.com/62x6r8

Но не могу создать подходящий XML файл структуры в битриксе.

 

Holster_int, ах, вот оно что. Объяснить, как сделать — не смогу. Но если хотите — помогу. Обращайтесь в личку.

 

Добрый день. Проблема с помощником импорта с сайта в 1с и при импорте пишет:
Получение данных с сайта:27.02.2015 16:07:44 — Загружено блоков XML: 3
27.02.2015 16:07:44 — Анализ данных XML:
27.02.2015 16:07:44 — Ошибка при разборе файла XML пришедшего с сайта. Анализ файлов будет прекращен. Если используется хранение пришедших файлов с сайта, то имя файла: 1.xml
27.02.2015 16:07:44 — Получено товаров: 0

Как с этим боротся??? Не могу загрузить товары

 

Александр Денисюк

Администратор

Сообщений: 5188
Баллов: 875
Регистрация: 16.10.2013

#6

0

27.02.2015 18:43:13

Цитата
Богдан написал:
Как с этим боротся??? Не могу загрузить товары

Найдите этот файл и смотрите, где нечитаемые символы XML. Ну а потом правьте данные в БУС

  • Фатальная ошибка space required after the public identifier
  • Фатальная ошибка python h нет такого файла или каталога
  • Фатальная ошибка putty no supported authentication methods available server sent publickey
  • Фатальная ошибка mysql что это
  • Фатальная ошибка mysql что означает