【问题标题】:No matching global declaration available for the validation root没有可用于验证根的匹配全局声明
【发布时间】:2012-01-15 14:29:53
【问题描述】:

背景

使用模式验证 XML 文档。

问题

问题的最简单形式显示在两个文件中。

XML 文档

<?xml version="1.0"?>

<recipe
  xmlns:r="http://www.namespace.org/recipe">

<r:description>
  <r:title>sugar cookies</r:title>
</r:description>

</recipe>

XSD 文档

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema
   version="1.0"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:r="http://www.namespace.org/recipe">

  <xsd:complexType name="recipe">
    <xsd:choice>
      <xsd:element name="description" type="descriptionType"
        minOccurs="1" maxOccurs="1" />
    </xsd:choice>
  </xsd:complexType>

  <xsd:complexType name="descriptionType">
    <xsd:all>
      <xsd:element name="title">
        <xsd:simpleType>
          <xsd:restriction base="xsd:string">
            <xsd:minLength value="5" />
            <xsd:maxLength value="55" />
          </xsd:restriction>
        </xsd:simpleType>
      </xsd:element>
    </xsd:all>
  </xsd:complexType>
</xsd:schema>

错误

来自xmllint的完整错误消息:

file.xml:4:元素配方:架构有效性错误:元素“配方”:没有可用于验证根的匹配全局声明。

问题

什么是正确的语法(或缺少哪些架构属性)以确保可以使用给定的架构来成功验证给定的 XML 文档?

【问题讨论】:

    标签: xml xsd xmllint


    【解决方案1】:

    只有全局元素定义可以用作根元素。您的架构只有复杂的类型,因此有错误。将&lt;xsd:complexType name="recipe"&gt; 更改为

    <xsd:element name="recipe">
      <xsd:complexType>
        <xsd:choice>
          <xsd:element name="description" type="descriptionType"
            minOccurs="1" maxOccurs="1" />
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
    

    阅读更多关于这个here

    【讨论】:

    • 将 elementFormDefault="qualified" 添加到您的 xs:schema 元素。这意味着架构中本地声明的元素被假定在目标命名空间中。这应该是默认设置,您应该将其视为样板文件——相反的场景,即本地元素不在命名空间中的情况非常罕见。
    【解决方案2】:

    您需要更改您的 XML 实例。您当前的说法是在命名空间 http://www.namespace.org/recipe 中有一个名为 description 的类型。但是,在您的 XSD 定义中,该名称空间中公开的唯一类型称为 recipe 和 descriptionType。

    所以要么在 XSD 架构中定义一个名为 description 的类型,要么更改你的实例以便正确引用 recipe 类型:

    <?xml version="1.0" encoding="utf-8"?>
    <r:recipe
      xmlns:r="http://www.namespace.org/recipe">
      <description>
        <title>sugar cookies</title>
      </description>
    </r:recipe>
    

    更新这只是解决方案的一半 - 另一半在 @Aravind 的答案中:https://stackoverflow.com/a/8426185/569662

    【讨论】:

    • 我认为description、title等也应该有命名空间(r:description等)。
    【解决方案3】:

    在我的实践中,我在两种情况下得到了No matching global declaration available for the validation root:

    • 如果 XSD 不包含在 @aravind-r-yarram's answer 中解释的 &lt;xsd:element name="recipe" .../&gt;。

    • 如果 XML 中的 &lt;recipe/&gt; 不包含 xmlns 属性。在这种情况下,添加 xmlns 会有所帮助:

        <recipe xmlns="http://www.namespace.org/recipe">
            ...
        </recipe>
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2021-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多