2016-09-17 66 views
2

我的程序可以返回2个XML,如:XSD耦合两个XML元素的值?

<RESPONSE> 
    <ERROR_ID>1</ERROR_ID> 
    <ERROR_MESSAGE>Parse error</ERROR_MESSAGE> 
</RESPONSE> 

<RESPONSE> 
    <ERROR_ID>2</ERROR_ID> 
    <ERROR_MESSAGE>Unexpected attribute</ERROR_MESSAGE> 
</RESPONSE> 

我尝试写一些XSD文件,以验证它们是否正常。这里是我结束了:

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="qualified"> 

    <xsd:element name="RESPONSE" type="Response"/> 

    <xsd:complexType name="Response"> 
     <xsd:all> 
      <xsd:element name="ERROR_ID" type="ErrorId"/> 
      <xsd:element name="ERROR_MESSAGE" type="ErrorMessage"/> 
     </xsd:all> 
    </xsd:complexType> 

    <xsd:simpleType name="ErrorId"> 
     <xsd:restriction base="xsd:positiveInteger"> 
      <xsd:enumeration value="1"/> 
      <xsd:enumeration value="2"/> 
     </xsd:restriction> 
    </xsd:simpleType> 

    <xsd:simpleType name="ErrorMessage"> 
     <xsd:restriction base="xsd:string"> 
      <xsd:enumeration value="Parse error"/> 
      <xsd:enumeration value="Unexpected attribute"/> 
     </xsd:restriction> 
    </xsd:simpleType> 

</xsd:schema> 

它验证罚款,但我想如果我能联系起来的错误ID错误消息,不让通过验证文件,其中的错误ID = 2将消息从去与错误id = 1:

<RESPONSE> 
    <ERROR_ID>2</ERROR_ID> 
    <ERROR_MESSAGE>Parse error</ERROR_MESSAGE> 
</RESPONSE> 

有一个很好的方法可以做到这一点?我的程序当然会返回更多的错误ID和消息。

也许更好的问题是,如果我甚至应该从XSD期望这样的验证?

回答

1

XSD 1.0无法基于另一个元素的值约束一个元素的值。

XSD 1.1可以这样做使用xsd:assert,但是你应该重新考虑你的设计...

替代设计建议:

  1. 不检查ERROR_ID - ERROR_MESSAGE在配对XSD。

  2. 连接具有错误消息的错误ID:针对更具体的错误元素名称

    <Error>1. Parse error</Error> 
    
  3. 使用的固定属性:

    <ParseError id="1" message="Parse error"/> 
    <UnexpectedAttributeError id="2" message="Unexpected attribute"/> 
    

无这些替代设计的需要XSD 1.1 。