我有一个架构,我想在列表上有一个特定的约束。在Employees
下的Firm
元素中,我需要员工列表中的所有DepartmentId
元素都相同。因此,如果Firm
的实例具有DepartmentId
1378
,则Firm
对象仅在所有Employees
具有相同ID时才有效。这可能与XSD有关吗?最好将其放在此处,因此在代码中针对XSD验证对象后,我不需要检查这一点。
<element name="Firm">
<complexType>
<sequence>
<element name="Name" type="string" />
<element name="Employees" type="tns:Employee" minOccurs="1" maxOccurs="unbounded" />
</sequence>
</complexType>
</element>
<complexType name="Employee">
<sequence>
<element name="EmployeeId" type="string" />
<element name="DepartmentId" type="string" />
<element name="Department" type="string" />
<element name="Name" type="string" />
<element name="Description" type="string" />
</sequence>
</complexType>
答案 0 :(得分:2)
你的约束不能在XSD 1.0中表达。
您的约束 可以通过xs:assert
在XSD 1.1中表达:
<xs:assert test="count(distinct-values(tns:Employees/tns:DepartmentId)) = 1"/>
在上下文中......
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://example.com/tns"
targetNamespace="http://example.com/tns"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
elementFormDefault="qualified"
vc:minVersion="1.1">
<xs:element name="Firm">
<xs:complexType>
<xs:sequence>
<xs:element name="Name" type="xs:string" />
<xs:element name="Employees" type="tns:Employee"
minOccurs="1" maxOccurs="unbounded" />
</xs:sequence>
<xs:assert test="count(distinct-values(tns:Employees/tns:DepartmentId))
= 1"/>
</xs:complexType>
</xs:element>
<xs:complexType name="Employee">
<xs:sequence>
<xs:element name="EmployeeId" type="xs:string" />
<xs:element name="DepartmentId" type="xs:string" />
<xs:element name="Department" type="xs:string" />
<xs:element name="Name" type="xs:string" />
<xs:element name="Description" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
然后此XML将有效:
<?xml version="1.0" encoding="UTF-8"?>
<Firm>
<Name></Name>
<Employees>
<EmployeeId></EmployeeId>
<DepartmentId>1378</DepartmentId>
<Department></Department>
<Name></Name>
<Description></Description>
</Employees>
<Employees>
<EmployeeId></EmployeeId>
<DepartmentId>1378</DepartmentId>
<Department></Department>
<Name></Name>
<Description></Description>
</Employees>
</Firm>
但此XML将无效:
<?xml version="1.0" encoding="UTF-8"?>
<Firm>
<Name></Name>
<Employees>
<EmployeeId></EmployeeId>
<DepartmentId>1378</DepartmentId>
<Department></Department>
<Name></Name>
<Description></Description>
</Employees>
<Employees>
<EmployeeId></EmployeeId>
<DepartmentId>9999</DepartmentId>
<Department></Department>
<Name></Name>
<Description></Description>
</Employees>
</Firm>
根据要求。