是否可以 xsd-验证是否存在具有确切属性的元素?

Is it possible to xsd-validate is an element with exact Attribute exists?

我正计划接收该结构:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
    <property key="DocumentType"   value="INV" />
    <property key="InvInternalNumber" value="i-1651-84" />
    <property key="OtherDynamicProperty" value="yes" />
</Document>

我确定文档类型并打算使用 "INV.xsd"

进行验证

哦,商家说发票必须有"InvInternalNumber"属性!

所以, 是否可以 xsd 验证“是否有 属性 "InvInternalNumber"”?

更新 XSD 已由 JaxbContext 生成。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="Document" type="Document"/>

  <xs:complexType name="Document">
    <xs:sequence>
      <xs:element name="property" type="property" nillable="true" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="property">
    <xs:sequence/>
    <xs:attribute name="key" type="xs:string"/>
    <xs:attribute name="value" type="xs:string"/>
  </xs:complexType>
</xs:schema>

这在 XSD 1.0 中似乎是不可能的,我认为如果您假设 InvInternalNumber 始终是您可以使用的第一个元素fixed 属性来做到这一点,但不幸的是,这是无效的。

Error cos-element-consistent: Error for type 'Document'. Multiple elements with name 'property', with different types, appear in the model group.

正如@Dag 所说,我认为唯一的解决方案是 link provided 中的 XSD 1.1。

XSD 1.0 不是为这项工作设计的:它假设元素名称决定了要应用的验证规则。解决它的一种方法是将 XML(使用 XSLT)转换为

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
    <DocumentType>INV</DocumentType>
    <InvInternalNumber>i-1651-84</InvInternalNumber>
    <OtherDynamicProperty>yes</OtherDynamicProperty>
</Document>

然后验证。 (您可以通过使用架构感知转换并验证结果文档一步完成此操作)。

如果验证规则不是由元素名称决定,而是由属性值决定(在您的情况下 property/@key),XSD 1.1 中条件类型分配的新功能可以使用。这允许您声明 property 元素的类型(因此,其 value 属性的类型)取决于 key 属性的值。