【发布时间】:2013-05-08 20:42:29
【问题描述】:
我想使用 xsd 模式文件验证 xml 文档。 xml 文档包含有关 windows 服务的信息,我想将 Service 中的 Name 属性设置为唯一值。
这是一个小的 xml 示例:
<?xml version="1.0" encoding="utf-8"?>
<Services xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://example.de/xml/services">
<Service Name="ALG" StartMode="Manual" State="Stopped">
<DisplayName>xyz</DisplayName>
</Service>
<Service Name="AllUserInstallAgent" StartMode="Manual" State="Stopped">
<DisplayName>xyz</DisplayName>
</Service>
<Service Name="AllUserInstallAgent" StartMode="Manual" State="Stopped">
<DisplayName>xyz</DisplayName>
</Service>
<Service Name="AllUserInstallAgent" StartMode="Manual" State="Stopped">
<DisplayName>xyz</DisplayName>
</Service>
</Services>
我尝试使用 xpath 进行以下操作:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.de/xml/services" attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://example.de/xml/services">
<xsd:element name="Services">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="Service">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="DisplayName" type="xsd:string" />
</xsd:sequence>
<xsd:attribute name="Name" type="xsd:string" use="required" />
<xsd:attribute name="StartMode" type="xsd:string" use="required" />
<xsd:attribute name="State" type="xsd:string" use="required" />
</xsd:complexType>
<xs:unique name="Unique-Name">
<xs:selector xpath="Service" />
<xs:field xpath="@Name" />
</xs:unique>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xs:schema>
但遗憾的是 xml 文档仍然有效。请注意,有些记录具有相同的Name。
我做错了什么?我发现了这个how to make an attribute unique in xml schema? 和XML XSD Schema - Enforce Unique Attribute Values in Schema。这里有什么不同?
【问题讨论】:
标签: xml validation xsd unique