Java HTML / XML How to - Use jaxb to bind random string to xs:boolean 'true'








Question

We would like to know how to use jaxb to bind random string to xs:boolean 'true'.

Answer

Java Model (Foo)

import javax.xml.bind.annotation.XmlRootElement;
/* w  w w  . j av a2 s  .  c  o m*/
@XmlRootElement
public class Foo {

    private boolean bar;

    public boolean isBar() {
        return bar;
    }

    public void setBar(boolean bar) {
        this.bar = bar;
    }

}

Demo

import java.io.StringReader;
import javax.xml.bind.*;
// w w  w. j av  a2 s . c o m
public class Main {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StringReader xml = new StringReader("<foo><bar>toast</bar></foo>");
        Foo foo = (Foo) unmarshaller.unmarshal(xml);

        System.out.println(foo.isBar());
    }

}