考虑以下(设计不佳?)XML 文档:
<?xml version="1.0" ?>
<command_result>
<param name="protocol_version" value="3"/>
<param name="player_state" value="navigator"/>
</command_result>
我想要做的是创建一个 XML 架构(XSD 格式),它根据 name
属性的实际值指定 value
属性的数据类型。
示例(伪代码):
if (param name = "protocol_version") then (param value type="xs:integer")
if (param name = "player_state") then (param value type="xs:string")
有没有办法在不修改源 XML 的情况下在模式文件中引入这样的条件语句?我研究了各种解决方案,但所有解决方案都需要以某种方式对源进行更改(例如设置 xsi:type)。
编辑
我当前的架构:
<?xml version="1.0" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="command_result">
<xs:complexType>
<xs:sequence>
<xs:element name="param" minOccurs="2" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required"/>
<!-- the following line needs to be modified somehow -->
<xs:attribute name="value" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
最佳答案
我认为这是不可能的。我能想到的唯一方法是这样的:
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/schema"
xmlns:tns="http://www.example.org/schema" elementFormDefault="qualified">
<element name="command_result">
<complexType>
<sequence>
<choice>
<element name="param" type="tns:protocol_version_type" />
<element name="param" type="tns:player_state_type" />
</choice>
</sequence>
</complexType>
</element>
<complexType name="protocol_version_type">
<attribute name="name" type="string" fixed="protocol_version" />
<attribute name="value" type="integer" />
</complexType>
<complexType name="player_state_type">
<attribute name="name" type="string" fixed="player_state" />
<attribute name="value" type="string" />
</complexType>
</schema>
但显然这是不允许的。当我在 Eclipse 中验证此架构时,出现以下错误:
- cos-nonambig: "http://www.example.org/schema":param and "http://www.example.org/schema":param (or elements from their substitution group) violate "Unique Particle Attribution". During validation against this schema, ambiguity would be created for those two particles.
- cos-element-consistent: Error for type '#AnonType_command_result'. Multiple elements with name 'param', with different types, appear in the model group.
如您所见,不能有两个具有相同名称但类型不同的元素。但这正是您的 XML 所需要的。
编辑:您甚至无法定义像这样的更简单的架构:
<element name="command_result">
<complexType>
<sequence>
<element name="param" type="tns:proptocol_version_type" />
<element name="param" type="tns:type2" />
</sequence>
</complexType>
</element>
在此版本中,没有 <choice>
给出,这意味着您的参数必须按给定的顺序出现。但是,虽然这删除了 nonambig
错误,element-consistent
错误仍然存在。
关于xml - XML 模式中的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13071282/