JAXB - Ignore element

自作多情 提交于 2019-11-27 14:57:00
skaffman

Assuming your JAXB model looks like this:

@XmlRootElement(name="foo")
public class Foo {

   @XmlElement(name="element1")
   String element1;

   @XmlElement(name="element2")
   String element2;

   @XmlElement(name="bar")
   Bar bar;
}

then simply removing the bar field from Foo will skip the <bar/> element in the input document.

Alternatively, annotated the field with @XmlTransient instead of @XmlElement, and it will also be skipped.

JAXB will ignore any unmapped properties.

Implementation wise (atleast in EcliseLink JAXB (MOXy), which I lead). When we are processing the contents via a SAX parser (i.e. the input was a SAXSource) then we swap out our ContentHandler that is responsible for building objects to one that does no processing for that section (org.eclipse.persistence.oxm.unmapped.UnmappedContentHandler). When a we are using processing the contents via a StAX parser we just advance to the next mapped event.

If you do have a property that corresponds to that node you can annotate it with @XmlTransient to make it an unmapped property.

All what you need it's mark field as @XmlTransient (@XmlTransient annotation which should hide fields that are not required). Example below

JavaEE:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "DeletedIds")
public class DeletedIds {

    @XmlElement(name = "DeletedId")
    private List<DeletedId> id;    

    @XmlTransient
    @XmlElement(name = "success")
    private String success;

    //getters&setters
}

@XmlAccessorType(XmlAccessType.FIELD)
public class DeletedId {

    private int id;

    //getters&setters
}

Xml:

<DeletedIds>
    <DeletedId>
        <id>1</id>
    </DeletedId>
    <DeletedId>
        <id>2</id>
    </DeletedId>
</DeletedIds>

You have to use a SAX parser, and a document handler that effectively "skips" the node of non-interest. You can't get around reading the bytes, but at least you can get around having them waste extra resources.

If your code requires a DOM tree, then you basically use a SAX document handler that generates DOM nodes, but "skips" the nodes of non-interest. Definitely less convenient that using the supplied DOM tree generators, but a decent trade-off is you can't live with the extra memory overhead of the unwanted nodes but you need the DOM tree.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!