Handling Missing Nodes with JAXB

I am currently using JAXB to parse XML files. I created the classes needed through the xsd file. However, the xml files I receive do not contain all the nodes declared in the generated classes. The following is an example of my xml file structure:

<root> <firstChild>12/12/2012</firstChild> <secondChild> <firstGrandChild> <Id> </name> <characteristics>Description</characteristics> <code>12345</code> </Id> </firstGrandChild> </secondChild> </root> 

I came across the following two cases:

  • node <name> present in the generated classes, but not in the XML files
  • node doesn't matter

In both cases, the value is null. I would like to be able to distinguish when a node is absent from an XML file and when it is present but has a null value. Despite my searches, I did not understand how to do this. Any help is more than welcome

Thank you so much for your time and help.

Hello

+5
source share
1 answer

A A JAXB implementation (JSR-222) will not invoke the set method on missing nodes. You can put logic in your set method to keep track of whether it has been called.

 public class Foo { private String bar; private boolean barSet = false; public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; this.barSet = true; } } 

UPDATE

JAXB will also treat empty nodes as having an empty String value.

Java Model

 import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Root { private String foo; private String bar; public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } public String getBar() { return bar; } public void setBar(String bar) { this.bar = bar; } } 

Demo

 import java.io.File; import javax.xml.bind.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum15839276/input.xml"); Root root = (Root) unmarshaller.unmarshal(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(root, System.out); } } 

Input.xml / output

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <root> <foo></foo> </root> 
+3
source

Source: https://habr.com/ru/post/952491/


All Articles