No matching global declaration available for the validation root перевод

This is my api.xml :

<import type="rest" resource="sonata.news.controller.api.post" name-prefix="sonata_api_news_post_" />
<import type="rest" resource="sonata.news.controller.api.comment" name-prefix="sonata_api_news_comment_" />

and this is how my routing_api.yml :

I’ve tried every single instruction, everything fails.

Каков правильный синтаксис при обращении к схеме при использовании пространств имен?

Создание XML-документа с использованием данной схемы.


.xml:9.20: Element '{http://example/buildings/1.0}old_buildings': No matching global declaration available for the validation root.
oldbuildings.xml - invalid
Problem


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

<buildings:old_buildings xmlns:buildings="http://example/buildings/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://example/buildings/1.0 oldbuildings_schema.xsd">
<building>
<name>Name</name>
<year_built era="BC">2000</year_built>
<story>...<story>
</building>
</buildings:old_buildings>
<?xml version="1.0" encoding="UTF-8"?>

<xs:schema targetNamespace="http://example/buildings/1.0/" 
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://example/buildings/1.0/"> <xs:element name="old_buildings"> <xs:complexType> <xs:sequence> <xs:element ref="building"/> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="building" type="buildingType"></xs:element> <xs:complexType name="buildingType"> <xs:sequence> <xs:element name="name" type="xs:string"/> <xs:element name="year_built" type="yearType"/> <xs:element name="story" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="yearType"> <xs:simpleContent> <xs:extension base="xs:positiveInteger"> <xs:attribute name="era" type="xs:string"/> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>

В вашем XML файле попробуйте

Xmlns: здания = “HTTP://example/buildings/1.0/”

с/final, как в объявлении xsd: xs:schema targetNamespace="http://example/buildings/1.0/"

While updating Magento 2.2.8 to 2.3.1

I’m facing issue when running bin/magento setup:upgrade

I get error:

The XML in file "/var/www/html/vendor/magento/module-store/etc/db_schema.xml" is invalid:
Element 'schema': No matching global declaration available for the validation root.
Line: 9

Anyone was facing this kind of issues?

Mohit Rane's user avatar

1 gold badge11 silver badges42 bronze badges

asked Apr 25, 2019 at 15:15

Andrei's user avatar

Check if any of your custom module has overridden any xsd file or SchemaLocator class. Comment that override and run the setup:upgrade again.

We got the same issue and found that our custom module had a plugin on below class:
Magento\Framework\Config\SchemaLocator. We commented this plugin in di.xml file and the issue is fixed.

answered Aug 1, 2019 at 7:39

Manu Mathew's user avatar

It looks to me that the schema.xsd file that controls the URN schema validation for the new db_schema.xml files is either missing or you have not cleared the cache.

vendor/magento/framework/Setup/Declaration/Schema/etc/schema.xsd

answered Apr 27, 2019 at 11:40

Daniel Kratohvil's user avatar

Daniel Kratohvil

1 gold badge14 silver badges22 bronze badges

Как я могу пропустить Element 'baz': No matching global declaration available for the validation root., line 1 именно эту ошибку?

Мне нужно проверить общий набор пар XML / XSD, которые не обязательно имеют одинаковый состав, поэтому жестко заданные / буквальные правила, применимые к конкретной структуре XML, не применяются.

XSD создается GMC Inspire Designer, который, как правило, не является валидатором XML и очень «расплывчат» в том, как он проверяет свой синтаксис. Проблема с глобальным объявлением возникает в моем локальном валидаторе, но не возникает в Inspire Designer из-за его слабой природы.

Как я могу указать конкретные наборы ошибок, которые будут генерироваться lxml, и продолжить проверку?

Используя следующий код:

#get a list of all files in the working directory that are .xml files
xml_files_from_cwd = [xml_f for xml_f in listdir(my_path) if isfile(join(my_path, xml_f)) 
                      and xml_f.lower().endswith(".xml")]

xml_validator = etree.XMLSchema(file= my_path)

for xml in xml_files_from_cwd:
    recovering_parser = etree.XMLParser(recover=True)
    xml_file = etree.parse(my_path + "/" +xml, parser=recovering_parser)

    successful = False 
    try:
        successful = xml_validator.assertValid(xml_file)
    except Exception as e:
        print(f"File not valid: {e}")
    
    if successful:
        print(f"No errors detected in {xml}.")

У меня возникают проблемы с проверкой XML-файла, в котором XML выглядит, как правило, следующим образом:

<baz>
  <bar BEGIN="1">
  ... [repeating elements here]
  </bar>
</baz>

И XSD, который следует этому формату:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="foo">
    <xsd:complexType>
      <xsd:sequence minOccurs="1" maxOccurs="1">
        <xsd:element name="bar" minOccurs="1" maxOccurs="unbounded">
                  .... [repeating elements here]
        </xsd:element>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

Пример ошибочно сформированного XML-файла, валидация которого приводит к ошибке:

No matching global declaration available for the validation root.

<schema xmlns=»http://www.w3.org/2001/XMLSchema» targetNamespace=»http://www.example.org/Devices» xmlns:tns=»http://www.example.org/Devices»  elementFormDefault=»qualified»>
   <element name=»devices»>
      <complexType>
         <sequence>
            <element name=»computerDevice»
                     type=»tns:computerDevice»
                     minOccurs=»3″
                     maxOccurs=»unbounded»/>
         </sequence>
      </complexType>
   </element>
<complexType name=»computerDevice»>
   <sequence>
      <element name=»name» type=»string»/>
      <element name=»origin» type=»string»/>
      <element name=»price» type=»tns:Range»/>
      <element name=»type» type=»tns:Type»/>
      <element name=»critical» type=»tns:Choice»/>
   </sequence>
<attribute name=»id» type=»ID» use=»required»/>
</complexType> 
<simpleType name=»Range»>
     <restriction base=»integer»>
       <minInclusive value=»0″/>
       <maxInclusive value=»1000″/>
     </restriction>
</simpleType>
<complexType name=»Type»>
   <sequence>
      <element name=»peripheral» type=»tns:Choice»/>
      <element name=»energy_consumption» type=»int»/>
      <element name=»cooler» type=»tns:Choice»/>
      <element name=»group» type=»string»/>
      <element name=»port»>
         <simpleType>
            <restriction base=»string»>
               <enumeration value=»HDMI»></enumeration>
               <enumeration value=»COM»></enumeration>
               <enumeration value=»LPT»></enumeration>
            </restriction>
         </simpleType>
      </element>
   </sequence>
</complexType>
<simpleType name=»Choice»>
   <restriction base=»string»>
      <pattern value=»Yes|No|yes|no»/>
   </restriction>
</simpleType>
</schema>

XML (с ошибкой):

<?xml version=»1.0″ encoding=»UTF-8″?>
<devices>
    <computerDevice id = «d1»>
        <name>Keyboard</name>
        <origin>Chine</origin>
        <price>10</price>
        <type>
            <peripheral>Yes</peripheral>
            <energy_consumption>2</energy_consumption>
            <cooler>No</cooler>
            <group>Input</group>
            <port>USB</port>
        </type>
        <critical>No</critical>
    </computerDevice>
    <computerDevice id = «d2»>
        <name>Monitor</name>
        <origin>Japanese</origin>
        <price>17</price>
        <type>
            <peripheral>Yes</peripheral>
            <energy_consumption>20</energy_consumption>
            <cooler>No</cooler>
            <group>Output</group>
            <port>HDMI</port>
        </type>
        <critical>Yes</critical>
    </computerDevice>
    <computerDevice id = «d3»>
        <name>printer</name>
        <origin>Azerbaijan</origin>
        <price>14</price>
        <type>
            <peripheral>Yes</peripheral>
            <energy_consumption>50</energy_consumption>
            <cooler>No</cooler>
            <group>Output</group>
            <port>COM</port>
        </type>
        <critical>No</critical>
    </computerDevice>
</devices>

XML (исправленный — см. строку №2):

<?xml version=»1.0″ encoding=»UTF-8″?>
<devices xmlns=»http://www.example.org/Devices»>
    <computerDevice id = «d1»>
        <name>Keyboard</name>
        <origin>Chine</origin>
        <price>10</price>
        <type>
            <peripheral>Yes</peripheral>
            <energy_consumption>2</energy_consumption>
            <cooler>No</cooler>
            <group>Input</group>
            <port>USB</port>
        </type>
        <critical>No</critical>
    </computerDevice>
    <computerDevice id = «d2»>
        <name>Monitor</name>
        <origin>Japanese</origin>
        <price>17</price>
        <type>
            <peripheral>Yes</peripheral>
            <energy_consumption>20</energy_consumption>
            <cooler>No</cooler>
            <group>Output</group>
            <port>HDMI</port>
        </type>
        <critical>Yes</critical>
    </computerDevice>
    <computerDevice id = «d3»>
        <name>printer</name>
        <origin>Azerbaijan</origin>
        <price>14</price>
        <type>
            <peripheral>Yes</peripheral>
            <energy_consumption>50</energy_consumption>
            <cooler>No</cooler>
            <group>Output</group>
            <port>COM</port>
        </type>
        <critical>No</critical>
    </computerDevice>
</devices>

Я создал схему XSD из DTD с помощью Visual Studio 2017, и при проверке в блокноте ++ получаю следующую ошибку:

"ERROR: Element 'rutas': No matching global declaration available for the validation root."

Я пробовал изменить кодировку, так как мой XML был в UTF-8, а XML из Visual Studio — в Windows-1252. Я также проверил HTML с предыдущим DTD, и все было в порядке.

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://tempuri.org/rutas" elementFormDefault="qualified" targetNamespace="http://tempuri.org/rutas" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="rutas">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="1" maxOccurs="unbounded" ref="ruta" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="ruta">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="tipo" />
        <xs:element ref="transporte" />
        <xs:element ref="duracion" />
        <xs:element ref="agencia" />
        <xs:element ref="descripcion" />
        <xs:element ref="personas" />
        <xs:element ref="inicio" />
        <xs:element minOccurs="1" maxOccurs="unbounded" ref="bibliografia" />
        <xs:element ref="recomendacion" />
        <xs:element minOccurs="1" maxOccurs="unbounded" ref="hito" />
      </xs:sequence>
      <xs:attribute name="nombre" type="xs:string" use="required" />
    </xs:complexType>
  </xs:element>
  <xs:element name="tipo" type="xs:string" />
  <xs:element name="transporte" type="xs:string" />
  <xs:element name="duracion" type="xs:string" />
  <xs:element name="agencia" type="xs:string" />
  <xs:element name="descripcion" type="xs:string" />
  <xs:element name="personas" type="xs:string" />
  <xs:element name="inicio">
    <xs:complexType>
      <xs:sequence>
        <xs:element minOccurs="0" maxOccurs="1" ref="fecha" />
        <xs:element minOccurs="0" maxOccurs="1" ref="hora" />
        <xs:element ref="lugar" />
        <xs:element ref="direccion" />
        <xs:element ref="coordenadas" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="fecha" type="xs:string" />
  <xs:element name="hora" type="xs:string" />
  <xs:element name="lugar" type="xs:string" />
  <xs:element name="direccion" type="xs:string" />
  <xs:element name="coordenadas">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute name="longitud" type="xs:string" use="required" />
          <xs:attribute name="latitud" type="xs:string" use="required" />
          <xs:attribute name="altitud" type="xs:string" use="required" />
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
  <xs:element name="bibliografia" type="xs:string" />
  <xs:element name="recomendacion" type="xs:string" />
  <xs:element name="hito">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="descripcion" />
        <xs:element ref="coordenadas" />
        <xs:element ref="distancia" />
        <xs:element minOccurs="1" maxOccurs="unbounded" ref="fotografia" />
        <xs:element minOccurs="0" maxOccurs="unbounded" ref="video" />
      </xs:sequence>
      <xs:attribute name="nombre" type="xs:string" use="required" />
    </xs:complexType>
  </xs:element>
  <xs:element name="distancia">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">`enter code here`
          <xs:attribute name="unidades" type="xs:string" use="required" />
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
  <xs:element name="fotografia" type="xs:string" />
  <xs:element name="video" type="xs:string" />
</xs:schema>
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>

<rutas
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation='rutas.xsd'>

    <ruta nombre = "Senda del oso"> 
    <tipo> Paisajística </tipo>
    <transporte> Bicicleta </transporte>
    <duracion> 3 horas </duracion>
    <agencia> Sin agencia </agencia>
    <descripcion> Constituye una ruta idónea para amantes del senderismo y cicloturistas. </descripcion>
    <personas> Forma física media/niños </personas>
    <inicio>
        <lugar> Tuñón </lugar>
        <direccion> AS-228 Km. 7 </direccion>
        <coordenadas longitud = "5º 58" latitud = "43º 17" altitud = "148m" />
    </inicio>
    <bibliografia> https://es.wikiloc.com/rutas-mountain-bike/asturias-senda-del-oso-via-verde-para-deporte-naturaleza-y-aventura-14435403 </bibliografia>
    <bibliografia> https://yendoporlavida.com/2017/03/13/senda-del-oso-en-bicicleta-por-asturias/ </bibliografia>
    <bibliografia> https://www.vallesdeloso.es/senda_del_oso.php </bibliografia>
    <recomendacion> 10 </recomendacion>
    <hito nombre = "Villanueva">
        <descripcion> Villanueva es una parroquia del concejo asturiano de Santo Adriano </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 16" altitud = "170m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <video> "Video.mp3" </video>
    </hito>
    <hito nombre = "Proaza">
        <descripcion> Pueblo de Asturias situado en el concejo de Proaza </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 15" altitud = "259m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    <hito nombre = "Entrago">
        <descripcion> Final de la ruta </descripcion>
        <coordenadas longitud = "6º 5" latitud = "43º 10" altitud = "494m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    </ruta>

    <ruta nombre = "Senda del oso"> 
    <tipo> Paisajística </tipo>
    <transporte> Bicicleta </transporte>
    <duracion> 3 horas </duracion>
    <agencia> Sin agencia </agencia>
    <descripcion> Constituye una ruta idónea para amantes del senderismo y cicloturistas. </descripcion>
    <personas> Forma física media/niños </personas>
    <inicio>  
        <fecha> 19-10-2019 </fecha>
        <hora> 17:00 </hora>
        <lugar> Tuñón </lugar>
        <direccion> AS-228 Km. 7 </direccion>
        <coordenadas longitud = "5º 58" latitud = "43º 17" altitud = "148m" />
    </inicio>
    <bibliografia> https://es.wikiloc.com/rutas-mountain-bike/asturias-senda-del-oso-via-verde-para-deporte-naturaleza-y-aventura-14435403 </bibliografia>
    <bibliografia> https://yendoporlavida.com/2017/03/13/senda-del-oso-en-bicicleta-por-asturias/ </bibliografia>
    <bibliografia> https://www.vallesdeloso.es/senda_del_oso.php </bibliografia>
    <recomendacion> 10 </recomendacion>
    <hito nombre = "Villanueva">
        <descripcion> Villanueva es una parroquia del concejo asturiano de Santo Adriano </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 16" altitud = "170m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <video> "Video.mp3" </video>
    </hito>
    <hito nombre = "Proaza">
        <descripcion> Pueblo de Asturias situado en el concejo de Proaza </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 15" altitud = "259m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    <hito nombre = "Entrago">
        <descripcion> Final de la ruta </descripcion>
        <coordenadas longitud = "6º 5" latitud = "43º 10" altitud = "494m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    </ruta>

    <ruta nombre = "Senda del oso"> 
    <tipo> Paisajística </tipo>
    <transporte> Bicicleta </transporte>
    <duracion> 3 horas </duracion>
    <agencia> Sin agencia </agencia>
    <descripcion> Constituye una ruta idónea para amantes del senderismo y cicloturistas. </descripcion>
    <personas> Forma física media/niños </personas>
    <inicio>  
        <fecha> 19-10-2019 </fecha>
        <hora> 17:00 </hora>
        <lugar> Tuñón </lugar>
        <direccion> AS-228 Km. 7 </direccion>
        <coordenadas longitud = "5º 58" latitud = "43º 17" altitud = "148m" />
    </inicio>
    <bibliografia> https://es.wikiloc.com/rutas-mountain-bike/asturias-senda-del-oso-via-verde-para-deporte-naturaleza-y-aventura-14435403 </bibliografia>
    <bibliografia> https://yendoporlavida.com/2017/03/13/senda-del-oso-en-bicicleta-por-asturias/ </bibliografia>
    <bibliografia> https://www.vallesdeloso.es/senda_del_oso.php </bibliografia>
    <recomendacion> 10 </recomendacion>
    <hito nombre = "Villanueva">
        <descripcion> Villanueva es una parroquia del concejo asturiano de Santo Adriano </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 16" altitud = "170m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <video> "Video.mp3" </video>
    </hito>
    <hito nombre = "Proaza">
        <descripcion> Pueblo de Asturias situado en el concejo de Proaza </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 15" altitud = "259m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    <hito nombre = "Entrago">
        <descripcion> Final de la ruta </descripcion>
        <coordenadas longitud = "6º 5" latitud = "43º 10" altitud = "494m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    </ruta>

    <ruta nombre = "Senda del oso"> 
    <tipo> Paisajística </tipo>
    <transporte> Bicicleta </transporte>
    <duracion> 3 horas </duracion>
    <agencia> Sin agencia </agencia>
    <descripcion> Constituye una ruta idónea para amantes del senderismo y cicloturistas. </descripcion>
    <personas> Forma física media/niños </personas>
    <inicio>  
        <fecha> 19-10-2019 </fecha>
        <hora> 17:00 </hora>
        <lugar> Tuñón </lugar>
        <direccion> AS-228 Km. 7 </direccion>
        <coordenadas longitud = "5º 58" latitud = "43º 17" altitud = "148m" />
    </inicio>
    <bibliografia> https://es.wikiloc.com/rutas-mountain-bike/asturias-senda-del-oso-via-verde-para-deporte-naturaleza-y-aventura-14435403 </bibliografia>
    <bibliografia> https://yendoporlavida.com/2017/03/13/senda-del-oso-en-bicicleta-por-asturias/ </bibliografia>
    <bibliografia> https://www.vallesdeloso.es/senda_del_oso.php </bibliografia>
    <recomendacion> 10 </recomendacion>
    <hito nombre = "Villanueva">
        <descripcion> Villanueva es una parroquia del concejo asturiano de Santo Adriano </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 16" altitud = "170m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <video> "Video.mp3" </video>
    </hito>
    <hito nombre = "Proaza">
        <descripcion> Pueblo de Asturias situado en el concejo de Proaza </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 15" altitud = "259m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    <hito nombre = "Entrago">
        <descripcion> Final de la ruta </descripcion>
        <coordenadas longitud = "6º 5" latitud = "43º 10" altitud = "494m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    </ruta>

    <ruta nombre = "Senda del oso"> 
    <tipo> Paisajística </tipo>
    <transporte> Bicicleta </transporte>
    <duracion> 3 horas </duracion>
    <agencia> Sin agencia </agencia>
    <descripcion> Constituye una ruta idónea para amantes del senderismo y cicloturistas. </descripcion>
    <personas> Forma física media/niños </personas>
    <inicio>  
        <fecha> 19-10-2019 </fecha>
        <hora> 17:00 </hora>
        <lugar> Tuñón </lugar>
        <direccion> AS-228 Km. 7 </direccion>
        <coordenadas longitud = "5º 58" latitud = "43º 17" altitud = "148m" />
    </inicio>
    <bibliografia> https://es.wikiloc.com/rutas-mountain-bike/asturias-senda-del-oso-via-verde-para-deporte-naturaleza-y-aventura-14435403 </bibliografia>
    <bibliografia> https://yendoporlavida.com/2017/03/13/senda-del-oso-en-bicicleta-por-asturias/ </bibliografia>
    <bibliografia> https://www.vallesdeloso.es/senda_del_oso.php </bibliografia>
    <recomendacion> 10 </recomendacion>
    <hito nombre = "Villanueva">
        <descripcion> Villanueva es una parroquia del concejo asturiano de Santo Adriano </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 16" altitud = "170m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <video> "Video.mp3" </video>
    </hito>
    <hito nombre = "Proaza">
        <descripcion> Pueblo de Asturias situado en el concejo de Proaza </descripcion>
        <coordenadas longitud = "6º" latitud = "43º 15" altitud = "259m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    <hito nombre = "Entrago">
        <descripcion> Final de la ruta </descripcion>
        <coordenadas longitud = "6º 5" latitud = "43º 10" altitud = "494m" />
        <distancia unidades = "km"> 3 </distancia>
        <fotografia> "Foto.jpg" </fotografia>
        <fotografia> "Foto.jpg" </fotografia>
    </hito>
    </ruta>
</rutas>
<!ELEMENT rutas (ruta+)>

<!ELEMENT ruta (tipo, transporte, duracion, agencia, descripcion, personas, inicio, bibliografia+, recomendacion, hito+)>
<!ELEMENT tipo (#PCDATA)>
<!ELEMENT transporte (#PCDATA)>
<!ELEMENT duracion (#PCDATA)>
<!ELEMENT agencia (#PCDATA)>
<!ELEMENT descripcion (#PCDATA)>
<!ELEMENT personas (#PCDATA)>
<!ELEMENT inicio (fecha?, hora?, lugar, direccion, coordenadas)>
    <!ELEMENT fecha (#PCDATA)>
    <!ELEMENT hora (#PCDATA)>
    <!ELEMENT lugar (#PCDATA)>
    <!ELEMENT direccion (#PCDATA)>
    <!ELEMENT coordenadas (#PCDATA)>
<!ELEMENT bibliografia (#PCDATA)>
<!ELEMENT recomendacion (#PCDATA)>
<!ELEMENT hito (descripcion, coordenadas, distancia, fotografia+, video*)>
    <!ELEMENT distancia (#PCDATA)>
    <!ELEMENT fotografia (#PCDATA)>
    <!ELEMENT video (#PCDATA)>
<!ATTLIST ruta nombre CDATA #REQUIRED>
<!ATTLIST coordenadas longitud CDATA #REQUIRED>
<!ATTLIST coordenadas latitud CDATA #REQUIRED>
<!ATTLIST coordenadas altitud CDATA #REQUIRED>
<!ATTLIST hito nombre CDATA #REQUIRED>
<!ATTLIST distancia unidades CDATA #REQUIRED>

С DTD проверка DTD: XML действителен.

Solution 2

Just shooting from the hip here, but have you tried converting the XML::Document holding the schema into an XML::Schema?

I don’t know that it would make a difference, but it’s worth a shot.

2 ответа

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

Например, если ваш документ будет действителен для:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="foo">
    <xs:complexType>
       <xs:choice>
         <xs:element name="bar">
            <xs:complexType>
                <xs:choice>
                    <xs:element name="baz"/>
                    <xs:element name="qux"/>
                </xs:choice>
            </xs:complexType>
         </xs:element>
         <xs:element name="quux">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="qux"/>
                </xs:sequence>
            </xs:complexType>
         </xs:element>
       </xs:choice>    
    </xs:complexType>
  </xs:element>
</xs:schema>

Этот документ может стать проблемой:

<foo>
  <quuz>
    <qux/>
    ...
  </quuz>
</foo>

Должен ли quuz быть bar или quux?

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

Это очень быстро усложняется, так как что-то действительное может зависеть от его содержимого, его структуры, значений атрибутов и т. Д. Очень скоро у вас будет так много вариантов для тестирования, что это станет невозможным — вы даже можете подумать о ситуациях, когда количество вариантов практически бесконечно, поэтому вам придется включить очень сложную логику, чтобы получить допустимое значение.

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

Примечание: в реальных жизненных сценариях вы действительно можете знать и ожидать, что вас ждет, и вы можете следовать стратегии проверки и, если она не удастся, неоднократно устранять проблему, потому что вы действительно знаете, какие есть варианты, до тех пор, пока вы дошли до конца документа. Мой ответ лишь подчеркивает, что здесь нет общего решения.

Дополнительно:  Где купить root права

16 Дек 2021 в 03:31

Похоже, что ответ на этот вопрос: «Можем ли мы продолжить проверку файла после начального состояния отказа?» — нет, поскольку нет гарантии, приведет ли какая-либо дальнейшая проверка к положительным результатам за пределами простых / тривиальных случаев.

16 Дек 2021 в 02:47

Change XML

According to your XSD, your XML should not be in a namespace and should not have multiple PermitFilter elements.

<?xml version="1.0" encoding="UTF-8"?>
<ShowAccesslists>
  <Access-List>
    <Type>Extended IP</Type>
    <Name>test</Name>
    <PermitFilter>
      <Filter>10 permit ip any any</Filter>
    </PermitFilter>
  </Access-List>
</ShowAccesslists>

Solution 1

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <!-- channel -->
  <xsd:element name="channel">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="username" type="xsd:string"/>
        <xsd:element name="password" type="xsd:string"/>
      </xsd:sequence>
      <xsd:attribute name="name" use="required" type="xsd:string" />
    </xsd:complexType>
  </xsd:element>

  <!-- hotel -->
  <xsd:element name="hotel">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="date">
          <xsd:complexType>
            <xsd:attribute name="from" use="required" type="xsd:string" />
            <xsd:attribute name="to" use="required" type="xsd:string" />
          </xsd:complexType>
        </xsd:element>
        <xsd:element ref="room" minOccurs="1"/>
      </xsd:sequence>
      <xsd:attribute name="id" use="required" type="xsd:string" />
    </xsd:complexType>
  </xsd:element>


  <!-- room -->
  <xsd:element name="room">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element name="allocation" type="xsd:string"></xsd:element>
      </xsd:sequence>
      <xsd:attribute name="id" use="required" type="xsd:string" />
    </xsd:complexType>
  </xsd:element>

  <!-- building all together -->
  <xsd:element name="request">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:element ref="channel" maxOccurs="1"/>
        <xsd:element ref="hotel" maxOccurs="1"/>
      </xsd:sequence>
    <xsd:attribute name="type" use="required" type="xsd:string" />
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

1 ответ

Change XSD

Your XML is in a namespace and has multiple PermitFilter elements.

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema elementFormDefault="qualified" attributeFormDefault="unqualified" 
            xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
            xmlns:sal="ODM://built-in//show_access-lists" 
            targetNamespace="ODM://built-in//show_access-lists">
  <xsd:complexType name="ShowAccesslists_def">
    <xsd:sequence>
      <xsd:element ref="sal:SpecVersion" minOccurs="0" />
      <xsd:choice minOccurs="0" maxOccurs="unbounded">
        <xsd:element ref="sal:Info" />
        <xsd:element name="Access-List" minOccurs="0" maxOccurs="1">
          <xsd:complexType>
            <xsd:sequence>
              <xsd:element name="Type" minOccurs="0" maxOccurs="1" type="xsd:string" />
              <xsd:element name="Name" minOccurs="0" maxOccurs="1" type="xsd:string" />
              <xsd:element name="DenyFilter" minOccurs="0" maxOccurs="1">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="Filter" minOccurs="0" maxOccurs="1" type="xsd:string" />
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
              <xsd:element name="PermitFilter" minOccurs="0" maxOccurs="unbounded">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="Filter" minOccurs="0" maxOccurs="1" type="xsd:string" />
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
            </xsd:sequence>
          </xsd:complexType>
        </xsd:element>
      </xsd:choice>
    </xsd:sequence>
  </xsd:complexType>
  <xsd:element name="SpecVersion" type="xsd:string" />
  <xsd:element name="Info" type="xsd:string" />
  <xsd:element name="ShowAccesslists" type="sal:ShowAccesslists_def" />
</xsd:schema>

XML Schema (XSD) Beginner Tutorial with Demo

09 : 44

XML Schema (XSD) Beginner Tutorial with Demo

Validate an XML file against an XSD

00 : 25

Validate an XML file against an XSD

DESP Data Reconcilliation

How to Generate XML, Resolve Errors, Validate PDF in XBRL

05 : 00

How to Generate XML, Resolve Errors, Validate PDF in XBRL

Validate XML with XSD in Notepad++

02 : 39

Validate XML with XSD in Notepad++

3. Add simple rules to an XSD, validate XML file

06 : 56

3. Add simple rules to an XSD, validate XML file

JAVA XML Validation (01) - Schema

Дополнительно:  Как включить камеру на ноутбуке sony vaio windows 7

13 : 40

JAVA XML Validation (01) — Schema

5. Using date, boolean, and default in XSD to validate XML

07 : 45

5. Using date, boolean, and default in XSD to validate XML

When updating to Magento 2.3.1 db_schema.xml is invalid: Element 'schema': No matching global...

01 : 45

JAVA XML Validation (02) - DTD

09 : 06

JAVA XML Validation (02) — DTD

XML validation using XSD in Spring boot.

08 : 33

XML validation using XSD in Spring boot.

Validate XML syntax and schema

04 : 39

Validate XML syntax and schema

CAMV XML Rules Validation Engine Tutorial and Test Suite Development

23 : 00

CAMV XML Rules Validation Engine Tutorial and Test Suite Development

How to Validate XML using an IS Schema in webMethods 10.7

06 : 09

How to Validate XML using an IS Schema in webMethods 10.7

Comments

  • Schema provided by Cisco extracted by running ‘show xsd-format cli show ip access-lists’ as recommended here http://www.cisco.com/c/en/us/td/docs/ios-xml/ios/xmlpi/command/xmlpi-cr-book/xmlpi-cr-p1.html#GUID-33CB3BAB-25B4-4FAD-9741-C7AFB483F701 is shown below:

    <?xml version="1.0" encoding="UTF-8"?>
      <xsd:schema elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
        <xsd:complexType name="ShowAccesslists_def">
          <xsd:sequence>
            <xsd:element ref="SpecVersion" minOccurs="0" />
            <xsd:choice minOccurs="0" maxOccurs="unbounded">
              <xsd:element ref="Info" />
              <xsd:element name="Access-List" minOccurs="0" maxOccurs="1">
                <xsd:complexType>
                  <xsd:sequence>
                    <xsd:element name="Type" minOccurs="0" maxOccurs="1" type="xsd:string" />
                    <xsd:element name="Name" minOccurs="0" maxOccurs="1" type="xsd:string" />
                    <xsd:element name="DenyFilter" minOccurs="0" maxOccurs="1">
                      <xsd:complexType>
                        <xsd:sequence>
                          <xsd:element name="Filter" minOccurs="0" maxOccurs="1" type="xsd:string" />
                        </xsd:sequence>
                      </xsd:complexType>
                    </xsd:element>
                    <xsd:element name="PermitFilter" minOccurs="0" maxOccurs="1">
                      <xsd:complexType>
                        <xsd:sequence>
                          <xsd:element name="Filter" minOccurs="0" maxOccurs="1" type="xsd:string" />
                        </xsd:sequence>
                      </xsd:complexType>
                    </xsd:element>
                  </xsd:sequence>
                </xsd:complexType>
              </xsd:element>
            </xsd:choice>
          </xsd:sequence>
        </xsd:complexType>
        <xsd:element name="SpecVersion" type="xsd:string" />
        <xsd:element name="Info" type="xsd:string" />
        <xsd:element name="ShowAccesslists" type="ShowAccesslists_def" />
      </xsd:schema>
    

    The XML fragment the router spits out is:

    <?xml version="1.0" encoding="UTF-8"?>
       <ShowAccesslists xmlns="ODM://built-in//show_access-lists">
        <Access-List>
          <Type>Extended IP</Type>
          <Name>test</Name>
          <PermitFilter>
            <Filter>10 permit ip any any</Filter>
          </PermitFilter>
          <PermitFilter>
            <Filter>20 permit tcp 0.0.0.1 255.255.255.0 any</Filter>
          </PermitFilter>
          <PermitFilter>
            <Filter>40 permit tcp host 10.22.1.128 10.11.79.0 0.0.0.255 eq domain</Filter>
          </PermitFilter>
          <PermitFilter>
            <Filter>50 permit tcp host 10.22.1.128 eq domain 10.11.79.0 0.0.0.255</Filter>
          </PermitFilter>
        </Access-List>
      </ShowAccesslists>
    

    Is the schema broken? How do I get it to validate?

  • What do I have to add to the schema to make the original XML fragment validate? Obviously to fix the multiple PermitFilter it should have macOccurs=»unbounded», but I don’t know how to add the namespace. The XML fragment always seems to come back with the namespace.

  • Answer updated — now shows how to change XML or how to change XSD to achieve successful validation.

Solution 3

I received the same cryptic error message for a different reason.

The first line of my schema file had an unprefixed namespace:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.sec.gov/edgar/document/thirteenf/informationtable" xmlns:ns1="http://www.sec.gov/edgar/common" targetNamespace="http://www.sec.gov/edgar/document/thirteenf/informationtable" elementFormDefault="qualified" attributeFormDefault="unqualified">

Note the ‘xmlns=’ attribute. This placed all the elements declared in the schema into the namespace http://www.sec.gov/edgar/document/thirteenf/informationtable (unless otherwise specified with a namespace prefix). But the XML file that I was trying to validate did not have a matching unprefixed/default namespace:

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

So its elements didn’t match the schema because they were in «different» namespaces. I hope this is useful to others.

02- Validate XML against Schema | java code

26 : 00

How to Fix XML declaration allowed only at the start of the document | Fix Yoast SEO Sitemap Error

06 : 52

JAVA XML Validation (01) - Schema

13 : 40

JAVA XML Validation (01) — Schema

13. Validating XML against XSD in C# using XmlReader

14 : 37

13. Validating XML against XSD in C# using XmlReader

When updating to Magento 2.3.1 db_schema.xml is invalid: Element 'schema': No matching global...

01 : 45

03-XML Schema Validation بالعربى

01 : 14 : 10

03-XML Schema Validation بالعربى

XML validation using XSD in Spring boot.

08 : 33

XML validation using XSD in Spring boot.

How to validate xml online

04 : 57

How to validate xml online

How to Validate XML using an IS Schema in webMethods 10.7

06 : 09

How to Validate XML using an IS Schema in webMethods 10.7

Datalist with free text error Select a valid choice. That choice is not one of the available choice

03 : 02

Datalist with free text error Select a valid choice. That choice is not one of the available choice

Comments

  • Error: Element ‘request’: No matching global declaration available for the validation root.

    Maybe it’s the namespace? Any ideas?

    XML

    <?xml version="1.0" encoding="UTF-8"?>
    <request type="test" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <channel name="channel">
        <username>user</username>
        <password>pass</password>
      </channel>
    
      <hotel id="1">
        <date from="2009-07-07" to="2009-07-17"/>
        <room id="1">
          <allocation>10</allocation>
        </room>
      </hotel>
    </request>   
    

    XSD

    <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    
      <!-- channel -->
      <xsd:element name="channel">
        <xsd:attribute name="name" use="required" type="xsd:string" />
        <xsd:sequence>
          <xsd:element username="name" use="required" type="xsd:string"/>
          <xsd:element password="country" use="required" type="xsd:string"/>
        </xsd:sequence>
      </xsd:element>
    
      <!-- hotel -->
      <xsd:element name="hotel">
        <xsd:attribute name="id" use="required" type="xsd:string" />
        <xsd:sequence>
          <xsd:element name="hotel">
            <xsd:attribute name="from" use="required" type="xsd:string" />
            <xsd:attribute name="to" use="required" type="xsd:string" />
          </xsd:element>
          <xsd:element ref="room" minOccurs="1"/>
        </xsd:sequence>
      </xsd:element>
    
    
      <!-- room -->
      <xsd:element name="room">
        <xsd:sequence>
          <xsd:element name="allocation" type="xsd:string"></xsd:element>
          <xsd:element ref="hotel" minOccurs="1"/>
        </xsd:sequence>
        <xsd:attribute name="id" use="required" type="xsd:string" />
      </xsd:element>
    
      <!-- building all together -->
      <xsd:element name="request">
        <xsd:attribute name="type" use="required" type="xsd:string" />
        <xsd:complexType>
          <xsd:sequence>
            <xsd:element ref="channel" maxOccurs="1"/>
            <xsd:element ref="hotel" maxOccurs="1"/>
          </xsd:sequence>
        </xsd:complexType>
      </xsd:element>
    </xsd:schema>
    

    Ruby code

    require "xml"
    
    document = LibXML::XML::Document.file("/tmp/test.xml")
    schema = LibXML::XML::Document.file("/tmp/request.xsd")
    
    result = document.validate_schema(schema) do |message,flag|
      log.debug(message)
      puts message
    end
    

Оцените статью
Master Hi-technology
Добавить комментарий