Configuring JAXB unmarshall process error handling

Assuming I have a schema that describes the class of the root element Rootthat contains List<Entry>where the class Entryhas a required field name.

Here's what it looks like in code:

@XmlRootElement 
class Root{
  @XmlElement(name="entry")
  public List<Entry> entries = Lists.newArrayList();
}

@XmlRootElement 
class Entry{
  @XmlElement(name="name",required=true)
  public String name;
}

If I put the following XML for unmarshalling:

<root>
  <entry>
    <name>ekeren</name>
  </entry>
  <entry>
  </entry>
</root>

I have a problem because the second record does not contain a name. Therefore unmarshall produces null.

Is there a way to configure JAXB on an unmarshall object Rootthat will only contain a “good” record?

+5
source share
1 answer

magic afterUnmarshal method, :

@XmlRootElement 
class Root{
  @XmlElement(name="entry")
  public List<Entry> entries = Lists.newArrayList();

  void afterUnmarshal(final Unmarshaller unmarshaller, final Object parent) {
    Iterator<Entry> iter = entries.iterator();
    while (iter.hasNext()) {
      if (iter.next().name == null) iter.remove();
    }
  }
}

EDIT:

, , , , . Pacher, . , / , afterUnmarshal (..)

UnmarshallingContext , . forward IDREF, . (Javadoc)

:

@XmlRootElement 
class Entry{
  @XmlElement(name="name",required=true)
  public String name;

  private boolean isValidEntry() {
    return name != null;
  }

  void afterUnmarshal(final Unmarshaller unmarshaller, final Object parent) {
    if (!isValidEntry()) {
      // entry not yet added to parent - use a patcher
      UnmarshallingContext.getInstance().addPatcher(new Patcher() {
        public void run() throws SAXException {
          ((Root)parent).removeEntry(this);
        }
      });
    }
  }
}

, API- Sun.

- , . - . , Bean Validation (JSR 303) , . Hibernate Validator ( , Hibernate ORM ). , () , ?

+5

All Articles