1.如何强制使用 CourierNumber 或 WorkLocationCooperative。我使用了如下所示的一种全局类型
在您给定的代码中,这两个定义并不紧密结合在一起(一个位于第二个子级别,另一个是深度嵌套的),因此我很难理解您的意思。
同一级别(相同 XPath)的两个元素不可能具有相同名称但类型不同。如果您尝试一下,您会得到(取决于您的 XSD 解析器):
E [Xerces] cos-element-consistent: Error for type 'LocationType'.
Multiple elements with name 'WorkArea', with different types, appear in the model group.
如果您可以使用 XSD 1.1,那么您可以通过使用断言来解决这个问题 https://stackoverflow.com/a/26620822/111575。由于唯一的信息WorkArea
是坐标,我假设你的意思是在两者之间切换CourierNumber
处于第一位置,或WorkArea
位于第二位置,但不是两者(实际上,它会有助于显示包含您想要的变体的实例文档)。
如果是这样,如何应用元素名称 CourierNumber 和 WorkLocationCooperative 中的类型,因为 'CourierNumber' 已包含类型 xsd:unsignedShort
这就是你真正的问题所在。由于您不使用命名类型(一切都是具有匿名复杂类型定义的一个大元素),因此您无法引用这些类型。一种解决方案是重复定义,但这可能会变得乏味并且有其局限性。
我在下面提供的解决方案只是将您的代码重构为“类型优先”方法。也就是说,您得到的不是一个大的(难以阅读的)元素定义,而是一小块命名类型定义。意见可能会有所不同,但我相信这更具可读性,而且绝对更灵活。 A关于这种方法的详细介绍以及它的缺点和特点可以在 XFront 上找到 http://www.xfront.com/ElementVersusType.html.
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
attributeFormDefault="unqualified"
elementFormDefault="qualified">
<!-- belonging to SO question https://stackoverflow.com/questions/33183835/how-to-make-either-of-the-fields-mandatory-in-xml-schema -->
<xsd:complexType name="CoordinatesType">
<xsd:sequence>
<xsd:element name="WorkLocationCoordinate" type="WorkLocationCoordinateType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="CourierNumberType">
<xsd:restriction base="xsd:unsignedShort"/>
</xsd:simpleType>
<xsd:complexType name="WorkLocationCoordinateType">
<xsd:sequence>
<xsd:element name="CoordinateX" type="xsd:unsignedByte" />
<xsd:element name="CoordinateY" type="xsd:unsignedByte" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="WorkAreaType">
<xsd:sequence>
<xsd:element name="WorkArea">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Coordinates" type="CoordinatesType" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="LocationType">
<xsd:choice>
<xsd:sequence>
<xsd:element name="CourierNumber" type="CourierNumberType" />
<xsd:element name="Roads" />
</xsd:sequence>
<xsd:sequence>
<xsd:element name="Roads" />
<xsd:element name="WorkArea" type="WorkAreaType" />
</xsd:sequence>
</xsd:choice>
</xsd:complexType>
<xsd:element name="Request">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Location" type="LocationType" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
这验证了以下任一情况:
<Request>
<Location>
<CourierNumber>12</CourierNumber>
<Roads></Roads>
</Location>
</Request>
Or this:
<Request>
<Location>
<Roads></Roads>
<WorkArea>
<WorkArea>
<Coordinates>
<WorkLocationCoordinate>
<CoordinateX>34</CoordinateX>
<CoordinateY>66</CoordinateY>
</WorkLocationCoordinate>
</Coordinates>
</WorkArea>
</WorkArea>
</Location>
</Request>