Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB. Get boolean from string

Tags:

java

jaxb

In my XML I have

<myelem required="false"/>

How I can read the required attribute as a boolean? I can read it as String and inside a getter do this: return new Boolean(required) But maybe there are some more elegant ways?

like image 764
WelcomeTo Avatar asked Jan 17 '23 08:01

WelcomeTo


1 Answers

Just simply use boolean for the member in your Java class:

@XmlAttribute
private boolean required;

Or, if you use getter-setter style of mapping:

@XmlAttribute
public boolean isRequired() {
    return required;
}

The JAXB unmarshaller is able to interpret "true" and "false" strings in the XML document as boolean value.

UPDATE:

I tested this with the following classes:

test/MyElem.java:

package test;

import javax.xml.bind.annotation.*;

@XmlRootElement(name="myelem")
public class MyElem {

    private boolean required;

    @XmlAttribute
    public boolean isRequired() {
        return required;
    }

    public void setRequired(boolean value) {
        required = value;
    }

}

Test.java:

import javax.xml.bind.*;
import java.io.*;
import test.*;

public class Test {
    public static void main(String[] args) {
        try {
            JAXBContext jc = JAXBContext.newInstance(MyElem.class);
            Unmarshaller u = jc.createUnmarshaller();
            Object o = u.unmarshal( new File( "test.xml" ) );   
            System.out.println(((MyElem)o).isRequired());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

And with the following input (test.xml):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myelem required="true"/>

I get the correct result on the console:

true
like image 157
buc Avatar answered Jan 30 '23 04:01

buc