Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling missing nodes with JAXB

Tags:

java

xml

jaxb

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 :

  1. The node <name> is present in the generated classes but not in the XML files
  2. The node has no value

In 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

like image 203
user2249868 Avatar asked Oct 22 '22 13:10

user2249868


1 Answers

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>
like image 147
bdoughan Avatar answered Oct 27 '22 10:10

bdoughan