问题描述
我想做类似于XMLStreamReader示例的事情,@ BlaiseDoughan在对但是,我需要根据子元素而不是当前节点属性做出过滤决策。
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没有像XMLEventReader这样的窥视API。例如,我想将以下XML解组到一个Gump对象中,该对象的记录列表最终仅包含1个项目,该记录的关联名称不以 Filtered-开头。
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-".
我正在使用Eclipselink 2.3.2v20111124-r10461
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<>();
}
}
推荐答案
最简单的方法是进行常规的解组,然后使用解组侦听器在解组后事件中清理集合。
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
这篇关于使用XMLStreamReader和StreamFilter基于子元素过滤出元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!