java - Force JAXB to Interpret Empty Element as Null not Empty String -


i have 1 particular element in xsd schema i'd jaxb treat empty element content null rather empty string. model classes generated xjc.

i've seen this answer marshalling empty string null globally, , i'm stuck ri of jaxb i'm guessing won't work me.

is there approach can take, given need 1 particular element?

since 1 element, below 1 way work jaxb implementation.

java model

foo

setup class use field access leveraging @xmlaccessortype annotation. initialize field corresponding element "". implement get/set methods treat "" null.

import javax.xml.bind.annotation.*;  @xmlrootelement @xmlaccessortype(xmlaccesstype.field) public class foo {      private string bar = "";      public string getbar() {         if(bar.length() == 0) {             return null;         } else {             return bar;         }     }      public void setbar(string bar) {         if(null == bar) {             this.bar = "";         } else {             this.bar = bar;         }     }  } 

demo code

below demo code can run see works.

input.xml

<?xml version="1.0" encoding="utf-8"?> <foo>     <bar/> </foo> 

demo

import java.io.file; import javax.xml.bind.*;  public class demo {      public static void main(string[] args) throws exception {         jaxbcontext jc = jaxbcontext.newinstance(foo.class);          unmarshaller unmarshaller = jc.createunmarshaller();         file xml = new file("src/forum18611294/input.xml");         foo foo = (foo) unmarshaller.unmarshal(xml);          system.out.println(foo.getbar());          marshaller marshaller = jc.createmarshaller();         marshaller.setproperty(marshaller.jaxb_formatted_output, true);         marshaller.marshal(foo, system.out);     }  } 

output

null <?xml version="1.0" encoding="utf-8" standalone="yes"?> <foo>     <bar></bar> </foo> 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -