开发者

jaxb, single item setter for collections

I want to make sure that an xml element-content is unmarshalled in upper case on my object.

public class SZM {

    String field01;
    @XmlElement(name="field01")
    public void setField01(String value) {this.field01 = value.toUpperCase();}
    public String getField01() {return field01;}

but how to do the same thing for every item in a collection? I want that any value read from the xml is capitalized.

@XmlElement
ArrayList<String>collection01;

Thanks in advance, Agostino

all the class, just in case:

package test.jaxb;

im开发者_运维问答port java.util.ArrayList;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class SZM {
    String field01;
    @XmlElement(name="field01")
    public void setField01(String value) {this.field01 = value.toUpperCase();}
    public String getField01() {return field01;}

    @XmlElement
    ArrayList<String>collection01;

}


You can use an XmlAdapter to manipulate the String values:

StringCaseAdapter

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class StringCaseAdapter extends XmlAdapter<String, String> {

    @Override
    public String unmarshal(String v) throws Exception {
        return v.toUpperCase();
    }

    @Override
    public String marshal(String v) throws Exception {
        return v.toLowerCase();
    }

}

SZM

You reference the XmlAdapter as:

package test.jaxb;

import java.util.ArrayList;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class SZM {
    String field01;

    @XmlElement(name="field01")
    @XmlJavaTypeAdapter(StringCaseAdapter.class)
    public void setField01(String value) {this.field01 = value;}
    public String getField01() {return field01;}

    @XmlElement
    @XmlJavaTypeAdapter(StringCaseAdapter.class)
    ArrayList<String>collection01;

}

input.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
    <collection01>def</collection01>
    <collection01>ghi</collection01>
    <field01>abc</field01>
</szm>

Demo

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

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

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        SZM szm = (SZM) unmarshaller.unmarshal(new File("input.xml"));

        System.out.println(szm.getField01());
        for(String item : szm.collection01) {
            System.out.println(item);
        }

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(szm, System.out);
    }

}

Output

ABC
DEF
GHI
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
    <collection01>def</collection01>
    <collection01>ghi</collection01>
    <field01>abc</field01>
</szm>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜