JAXB (JSR-222)规范没有定义char
/的XML 表示Character
。默认情况下,JAXB 引用实现将 a 转换Character
为xs:unsignedShort
类型。这意味着它需要这样的文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Emp>
<name>Jane Doe</name>
<dateCheckFlag>89</dateCheckFlag>
</Emp>
xml适配器
您将能够使用 anXmlAdapter
来获取您正在寻找的 XML。AnXmlAdapter
允许您将一个对象转换为另一个对象以更改 XML 表示。
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class CharacterAdapter extends XmlAdapter<String, Character> {
@Override
public Character unmarshal(String string) throws Exception {
return string.charAt(0);
}
@Override
public String marshal(Character character) throws Exception {
return new String(new char[] {character});
}
}
雇员
注解@XmlJavaTypeAdapter
用于指定.XmlAdapter
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name = "Emp")
@XmlAccessorType(XmlAccessType.FIELD)
class Emp {
String name;
@XmlJavaTypeAdapter(CharacterAdapter.class)
Character dateCheckFlag;
}
演示
下面是一些将 XML 转换为对象模型的代码。
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Emp.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum15240702/input.xml");
Emp emp = (Emp) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(emp, System.out);
}
}
输入.xml/输出
<?xml version="1.0" encoding="UTF-8"?>
<Emp>
<name>Jane Doe</name>
<dateCheckFlag>Y</dateCheckFlag>
</Emp>