java - Handling missing nodes with JAXB -


i using jaxb parse xml files. generated classes needed through xsd file. however, xml files receive not contain nodes declared in generated classes. following example of 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 confronted following 2 cases :

  1. the node <name> present in generated classes not in xml files
  2. the node has no value

in both cases, value set null. able differentiate when node absent xml file , when it's present has null value. despite searches, didn't figure out way so. more welcome

thank in advance time , help

regards

a jaxb (jsr-222) implementation won't call set method absent nodes. put logic in set method track whether or not 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 treat empty nodes having 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> 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -