【问题标题】:XSD to couple values of two XML elements?XSD 耦合两个 XML 元素的值?
【发布时间】:2016-09-17 19:32:50
【问题描述】:

我的程序可以返回 2 个 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 进行这样的验证?

【问题讨论】:

    标签: xml xsd xsd-validation xml-validation


    【解决方案1】:

    XSD 1.0 不能根据另一个元素的值来约束一个元素的值。

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

    替代设计建议:

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

    2. 将错误 ID 与错误消息连接起来:

      <Error>1. Parse error</Error>
      
    3. 针对更具体的错误元素名称使用固定属性:

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

    这些替代设计都不需要 XSD 1.1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      相关资源
      最近更新 更多