【问题标题】:XML Validation against XSD : cvc-complex-type.2.4.a针对 XSD 的 XML 验证:cvc-complex-type.2.4.a
【发布时间】:2019-09-18 11:12:01
【问题描述】:

目前我正在使用 javax.xml.validation.Validator 针对给定的 xsd 验证 xml。我已经设置了自定义错误处理程序来获取所有异常,而不是在第一个异常时退出。

Sample xsd:
        <xs:element type="xs:string" name="att1"/>
        <xs:element type="xs:string" name="att2"/>
        <xs:element type="xs:string" name="att3"/>
        <xs:element type="xs:string" name="att4"/>

In xml if att2 and att3 values are not there, I am getting below exception.
cvc-complex-type.2.4.a: Invalid content was found starting with element 'att4'. One of '{"https://******":att2}' is expected.

But I need exception to be like this i.e. both att2 and att3 should be shown in expected list.
cvc-complex-type.2.4.a: Invalid content was found starting with element 'att4'. One of '{"https://******":att2, "https://******":att3}' is expected.

我怎样才能做到这一点?

【问题讨论】:

    标签: java xml validation xsd schema


    【解决方案1】:

    作为第二个元素,xsd指定att2,把你提供的att4
    作为第三个元素,xsd 指定 att3 但您没有提供任何元素。
    您可以尝试将元素 att2 和/或 att3 设置为可选:

    minOccurs="0" maxOccurs="1"
    

    如果不行,你可以试试:

    <xs:element type="xs:string" name="att1"/>
    <xs:choice minOccurs="0" maxOccurs="2">
            <xs:sequence>
                <xs:element maxOccurs="1" name="att2" type="xs:string" />
                <xs:element maxOccurs="1" name="att3" type="xs:string" />
            </xs:sequence>
    </xs:choice>
     <xs:element type="xs:string" name="att4"/>
    

    【讨论】:

    • 现在在这两种情况下都没有显示任何异常
    【解决方案2】:

    验证器实现为有限状态机。它计算从一种状态到另一种状态的允许转换。阅读att1 元素后,唯一允许的转换是到att2,这就是它告诉您的内容。探索整个有限状态机并计算出 att4 如果有一个 att2 然后是一个 att3 将是有效的,这还不够聪明。

    Saxon 验证器比这好一点,但也只是一点点:它不会给你你在这里寻找的东西。

    如果有什么安慰的话,XSD 验证器通常比正则表达式引擎做得更好(它们本质上就是这样);正则表达式引擎通常只会告诉您输入与正则表达式不匹配,并且不知道原因。

    【讨论】:

      猜你喜欢
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 2023-03-09
      • 2018-08-24
      • 2015-05-05
      相关资源
      最近更新 更多