xsd 验证同时抱怨缺少属性和错误属性

ens*_*nic 4 xml schema xsd-validation

我从 xsd 验证中得到了一些精神分裂的行为。此链接显示了 xml 和 xsd + 在线模式验证器中的错误。当我使用 xmllint 在本地运行此命令时

xmllint --noout --nonet --schema devhelp2.xsd tester.devhelp2
Run Code Online (Sandbox Code Playgroud)

我收到类似的警告:

tester.devhelp2:5: element sub: Schemas validity error : Element '{urn:devhelp}sub', attribute 'name': The attribute 'name' is not allowed.
tester.devhelp2:5: element sub: Schemas validity error : Element '{urn:devhelp}sub', attribute 'link': The attribute 'link' is not allowed.
tester.devhelp2:5: element sub: Schemas validity error : Element '{urn:devhelp}sub': The attribute '{urn:devhelp}name' is required but missing.
tester.devhelp2:5: element sub: Schemas validity error : Element '{urn:devhelp}sub': The attribute '{urn:devhelp}link' is required but missing.
Run Code Online (Sandbox Code Playgroud)

但这暗示命名空间有问题。

附:

我可以通过完全删除 xmlns (取自zvon.org)来验证它。请参阅此处的新在线验证器示例- 不过我仍然想了解它,是否有保留 xmlns 的解决方案?

Chr*_*fer 5

简化示例

我将您的示例简化为以下 XML 架构。

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  targetNamespace="urn:devhelp"
  xmlns="urn:devhelp"
  elementFormDefault="qualified">

  <xsd:attribute name="title" type="xsd:string"/>

  <xsd:element name="book">
    <xsd:complexType>
      <xsd:attribute ref="title" use="required"/>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>
Run Code Online (Sandbox Code Playgroud)

和这个 XML

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<book xmlns="urn:devhelp" title="tester Reference Manual"/>
Run Code Online (Sandbox Code Playgroud)

验证错误

无效。
错误 - 第 2 行、第 60 行:org.xml.sax.SAXParseException;行号:2;列数:60;cvc-complex-type.3.2.2:属性“title”不允许出现在元素“book”中。
错误 - 第 2 行、第 60 行:org.xml.sax.SAXParseException;行号:2;列数:60;cvc-complex-type.4:属性“title”必须出现在元素“book”上。

相互矛盾的验证错误很好地表明命名空间存在问题。

规范:XML 1.0 中的命名空间

规格说明

6.2 命名空间默认

...默认命名空间声明并不直接应用于属性名称;无前缀属性的解释由它们出现的元素决定。

第一个子句解释了属性不会继承元素的默认名称空间声明。因此/book/@title没有命名空间,而您的 XML 模式需要title命名空间的属性urn:devhelp

第二个子句很棘手,因为它很容易被误解。它只是说属性不需要命名空间,因为它们可以根据周围的元素以不同的方式使用。

一个例子也提到了这种行为:

6.3 属性的唯一性

...但是,以下各项都是合法的,第二个是合法的,因为默认命名空间不适用于属性名称:
...
<x xmlns:n1="http://www.w3.org" xmlns="http: //www.w3.org">
  <good a="1" b="2" />
  <good a="1" n1:a="2" />
</x>

解决方案

显式设置属性的命名空间。

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<book xmlns="urn:devhelp" xmlns:mine="urn:devhelp" mine:title="tester Reference Manual"/>
Run Code Online (Sandbox Code Playgroud)

或避免在以下范围之外定义属性complexType

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://www.w3.org/2001/XMLSchema"
  xmlns:mine="urn:devhelp"
  targetNamespace="urn:devhelp"
  elementFormDefault="qualified">

  <xsd:element name="book">
    <xsd:complexType>
      <xsd:attribute name="title" type="xsd:string" use="required"/>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>
Run Code Online (Sandbox Code Playgroud)