Java – use JAXB to handle missing nodes
I am currently using JAXB to parse XML files I generated the required classes through the XSD file However, the XML file I received does not contain all the nodes declared in the generated class Here 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 face the following two situations:
>The node < name > exists in the generated class but not in the XML file > the node has no value
In both cases, the value is set to null I want to be able to distinguish when the node does not exist in the XML file and when it exists but has a null value Despite my search, I haven't come up with a way Any help is very welcome
Thank you very much for your time and help
to greet
Solution
The JAXB (JSR - 222) implementation does not call the set method for missing nodes You can place logic in the set method to track 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 also treats an empty node as a value with an empty string
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; } }
demonstration
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>