Ошибка разбора xml неправильное имя тега

Содержание:

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>

I am getting this error:

Error parsing XML: mismatched tag.

If anyone knows how to fix this, can you please let me know what I’m missing, thank you.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/android" >

    <Button
        android:id="@+id/btnChangeImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Image" >

</LinearLayout>

Shane van Wyk's user avatar

asked Apr 30, 2015 at 23:52

Harrison's user avatar

The closing tags for the <ImageView> and <Button> tags are missing.

You can add a / at the end of the tags to make them self-closing:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/android" />

    <Button
        android:id="@+id/btnChangeImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Image" />

</LinearLayout>

answered May 1, 2015 at 0:03

Guffa's user avatar

GuffaGuffa

685k108 gold badges735 silver badges1002 bronze badges

Agree with the above answers, but I think the answers can be added to by showing you a simple way to debug this yourself for the future (teach a man to fish…).

Modern browsers have XML parsers built in. Open your original file using Internet Explorer. It gives this error message:

End tag 'LinearLayout' does not match the start tag 'Button'. 

Once you close the Button node, save the file and open it again. It gives you this error:

End tag 'LinearLayout' does not match the start tag 'ImageView'.

Close that tag, save and re-open file. The well formed XML renders in the browser. While normally I an not a big proponent of IE, it gives a better error message than Chrome, and it allows you to collapse and expand each level of nested XML, which is really helpful for more complex XML. I hope this technique helps you out in the future.

answered May 1, 2015 at 0:22

E LaRoche's user avatar

E LaRocheE LaRoche

1,1061 gold badge7 silver badges8 bronze badges

1

Need to close the Button and ImageView Tags.

For every Tag / Node / Element you open, you need to also close them.

For example: if you open with <Tag> you need to close with </Tag> or add a slash at the end of the tag like this: <Tag />

Solution to your problem is bellow:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/android" /> <!-- This one here -->

    <Button
        android:id="@+id/btnChangeImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Image" /> <!-- This one here -->

</LinearLayout>

OR

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/android" >
    </ImageView> <!-- This one here -->

    <Button
        android:id="@+id/btnChangeImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Image" >
    </Button> <!-- This one here -->

</LinearLayout>

answered May 1, 2015 at 0:03

Shane van Wyk's user avatar

Shane van WykShane van Wyk

1,8601 gold badge26 silver badges62 bronze badges

У меня есть серьезная проблема с получением данных из 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 не указано значение для узла имя криптопровайдера
  • Ошибка разбора xml код ошибки 330
  • Ошибка разбора xml excel
  • Ошибка разбора xml error code 1
  • Ошибка разбора xml 1 6 фатальная ошибка char 0x0 out of allowed range