Filtering out elements based on sub elements with

2019-07-21 18:22发布

问题:

I want to do something similar to XMLStreamReader example @BlaiseDoughan gave in his response to JAXB filtered parsing however I need to make the filtering decision based on sub elements not current node attributes.

XMLStreamReader does not have a peek API like XMLEventReader. For example, I want to unmarshall the following XML into a Gump object whose records list ends up only containing 1 item, the record whose associated name does not start with "Filtered-".

I'm using Eclipselink 2.3.2v20111124-r10461

<gump>
    <foo>Some text</foo>
    <bar>1.245</bar>
    <records>
        <record>
            <name>Filtered-Counter</name>
            <value>1</value>
        </record>
        <record>
            <name>Golden</name>
            <value>shiny</value>
        </record>
    </records>
    <baz>1234</baz>
</gump>

Gump.java

@XmlRootElement(name = "gump")
@XmlAccessorType(XmlAccessType.FIELD)
public class Gump implements Serializable {

    private String foo;
    private String bar;
    private String baz;

    @XmlElementWrapper
    @XmlElement(name = "record")
    private List<Record> records;

    // .. Field getters/setters 

    public Gump() {
      records = new ArrayList<>();
    }
}

回答1:

The easiest thing to do would be to do a regular unmarshal, and then use an unmarshal listener that cleans up the collection on the after unmarshal event.

  • http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/Unmarshaller.Listener.html
  • http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/Unmarshaller.html#unmarshalEventCallback