Java使用JAXB处理XML时仅导出新增数据的实现问题咨询
问题解答
1. type字段泛化实现
匹配到符合条件的Institution对象i后,直接读取i的type属性赋值给新对象即可,无需硬编码:
把newInstitution.setType("School");替换为newInstitution.setType(i.getType());
如果你的期望输出不需要Institution的type属性,直接删掉这行赋值代码即可。
2. 输出仅包含新增节点
不要复用反序列化得到的xmlentries对象做序列化,新建一个空的Institutions根对象,仅把你新增的Institution对象放入其中即可。具体操作:
- 不需要把
newInstitution添加到原有的institutionList里 - 新建
Institutions实例,初始化它的Institution列表,把newInstitution添加到这个新列表中 - 用这个新建的
Institutions实例执行marshall操作即可
3. aftermarshall方法调用说明
aftermarshall是JAXB提供的序列化回调钩子,它会由JAXB框架在序列化操作完成后自动触发,不支持在主程序中直接手动调用,它的作用是供开发者自定义序列化完成后的后置逻辑,比如数据校验、额外字段加工等。
修改后的完整代码示例
public static void main(String[] args) { try { File xmlFile = new File("sample.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Institutions.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Institutions xmlentries = (Institutions) jaxbUnmarshaller.unmarshal(xmlFile); List<Institution> institutionList = xmlentries.getInstitution(); Institution newInstitution = null; // 匹配逻辑保留 for(Institution i : institutionList) { if(i.getType().equals("School")) { newInstitution = new Institution(); newInstitution.setPlace("Augsburg"); // 泛化获取type,若不需要type属性可直接删除此行 // newInstitution.setType(i.getType()); List<String> subjectList = new ArrayList<>(); subjectList.add("Math"); subjectList.add("Science"); newInstitution.setSubjects(subjectList); break; } } if(newInstitution!=null) { // 新建空的根对象,仅放入新增节点 Institutions outputRoot = new Institutions(); outputRoot.setInstitution(new ArrayList<>()); outputRoot.getInstitution().add(newInstitution); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 序列化新的根对象 marshaller.marshal(outputRoot, new File("outputsample.xml")); } }catch (JAXBException | FactoryConfigurationError e) { e.printStackTrace(); } }
内容的提问来源于stack exchange,提问作者Rakshan Premsagar Kapikad
相关产品推荐
相关产品推荐

