I am currently using JAXB to parse xml files. I generated the classes needed through an 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's structure:
<root>
<firstChild>12/12/2012</firstChild>
<secondChild>
<firstGrandChild>
<Id>
</name>
<characteristics>Description</characteristics>
<code>12345</code>
</Id>
</firstGrandChild>
</secondChild>
</root>
I am confronted with the following two cases :
<name>
is present in the generated classes but not in the XML filesIn both cases, the value is set to null. I would like to be able to differentiate when the node is absent from the XML file and when it's present but has a null value. Despite my searches, I didn't figure out a way to do so. Any help is more than welcome
Thank you so much in advance for your time and help
Regards
A JAXB (JSR-222) implementation won't call the set method for absent nodes. You could put logic in your set method to track whether or not 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 a value of 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;
}
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With