我想确保在我的对象上以大写形式解组xml元素内容。
public class SZM {
String field01;
@XmlElement(name="field01")
public void setField01(String value) {this.field01 = value.toUpperCase();}
public String getField01() {return field01;}
但如何为集合中的每个项目做同样的事情?我希望从xml读取的任何值都是大写的。
@XmlElement
ArrayList<String>collection01;
提前致谢, 阿戈斯蒂诺
所有课程,以防万一:
package test.jaxb;
import 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;
}
答案 0 :(得分:1)
您可以使用XmlAdapter来操作String值:
<强> 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 强>
您将XmlAdapter引用为:
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>
<强>演示强>
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);
}
}
<强>输出强>
ABC
DEF
GHI
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
<collection01>def</collection01>
<collection01>ghi</collection01>
<field01>abc</field01>
</szm>