2

我有路线,

<from uri="a">
<to uri="validator:schema.xsd">
<to uri="b">

假设正在验证的 XML 文件缺少两个元素,验证器似乎会在找到第一个缺少的元素并返回一条消息说它丢失时停止。

是否可以继续验证 XML 文件以查找任何其他丢失的元素并将其返回到错误消息中,以便发件人不必继续发送以找出哪些元素丢失或无效?

4

1 回答 1

0

如果验证失败,验证器组件将抛出SchemaValidationException 。此异常包含方法getError()返回List<org.xml.sax.SAXParseException>。您可以使用它来将消息转换为List<org.xml.sax.SAXParseException>onException 块。

以下代码捕获 SchemaValidationException,将 body 转换为SchemaValidationException.getErrors()并将异常标记为continued,以继续路由并在输出路由上返回此列表。

from("timer:simple?period=1000")
    .setBody(constant(XML_INVALID))
    .to("direct:a");

from("direct:a")
    .onException(SchemaValidationException.class)
        .to("direct:validationErrors")
        .continued(true)
        .end()
    .to("validator:test.xsd")
    .to("log:result");

from("direct:validationErrors")
    .setBody(simple("${property.CamelExceptionCaught.errors}"))
    .end();

注意:此示例已使用以下资源进行测试

XML_INVALID

<?xml version="1.0" encoding="utf-8"?>
<shiporder orderid="str1234">
  <orderperson>str1234</orderperson>
  <shipto>
    <name>str1234</name>
    <address>str1234</address>
  </shipto>
  <item>
    <quantity>745</quantity>
    <price>123.45</price>
  </item>
</shiporder>

w3schools.com复制的 test.xsd

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

<!-- definition of simple elements -->
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>

<!-- definition of attributes -->
<xs:attribute name="orderid" type="xs:string"/>

<!-- definition of complex elements -->
<xs:element name="shipto">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="name"/>
            <xs:element ref="address"/>
            <xs:element ref="city"/>
            <xs:element ref="country"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="item">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="title"/>
            <xs:element ref="note" minOccurs="0"/>
            <xs:element ref="quantity"/>
            <xs:element ref="price"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="shiporder">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="orderperson"/>
            <xs:element ref="shipto"/>
            <xs:element ref="item" maxOccurs="unbounded"/>
        </xs:sequence>
        <xs:attribute ref="orderid" use="required"/>
    </xs:complexType>
</xs:element>

</xs:schema>
于 2017-12-02T13:09:48.263 回答