开发者

JAXB parsing "minOccours" - Problem with unmarshling

开发者 https://www.devze.com 2023-04-07 00:21 出处:网络
I have following XSD which i used to generated JAXB objects <xs:complexType name=\"packageType\">

I have following XSD which i used to generated JAXB objects

<xs:complexType name="packageType">
    <xs:sequence>
        <xs:element ref="package" minOccurs="0" maxOccurs="unbounded"/>
        <xs:element ref="dependencies" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute name="id" type="xs:NMTOKEN" use="required"/>
</xs:complexType>

Now, If i receive an XML

  1. no dependency tag
  2. empty dependency tag i.e.

Sample XML

<package id="FA33" required="false" empty="false">
  <dependencies />
</package>

In the above example, If i remove the "dependencies" empty tag, JAXB throws "unexpected end of package" error.

Since the minOccours is there, both of these开发者_高级运维 scenario shouldn't make a difference. But in my case, JAXB is unable to unmarsh the given xml in case1 i.e. if there is no dependency tag. If an empty dependencies tag is there then it goes fine.

Is it expected behavior or its doing something wrong?

P.S: I am using Jaxb 1.3


How about using JAXB 2?

JAXB 1 used to validate on unmarshall. This was a problem since you couldn't really unmarshall invalid XML with missing mandatory elements etc.

As far as I remember, I used to solve this problem by:

  • Registering an "ignoring" validation handler
  • Generating schema-derived classes with a patched version of jaxb-xjc

The handler is as follows:

import javax.xml.bind.ValidationEventHandler;

/**
 * Validation handler which ignores all the validation events.
 */
public class IgnoringValidationEventHandler implements ValidationEventHandler {

    /**
     * Static instance.
     */
    public static final ValidationEventHandler INSTANCE = new IgnoringValidationEventHandler();

    /**
     * Simply returns <code>true</code>
     * 
     * @param event
     *            ignored;
     * @return Always returns <code>true</code>.
     */
    public boolean handleEvent(javax.xml.bind.ValidationEvent event) {
        return true;
    }
}

Register it via marshaller.setEventHandler(IgnoringValidationEventHandler.INSTANCE);.

As for the patched jaxb-xjc, you may contact me via valikov(at)gmx.net, I can send you the jar.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号