Filtering out elements based on sub elements with XMLStreamReader and StreamFilter

半城伤御伤魂 提交于 2020-01-24 15:36:08

问题


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


来源:https://stackoverflow.com/questions/22695541/filtering-out-elements-based-on-sub-elements-with-xmlstreamreader-and-streamfilt

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