我需要将xml内容读入对象图。
我的xml格式是:
<?xml version="1.0"?>
<format>
<fileheader>
<tag name="firstname" length="2" order="1" padding=""></tag>
<tag name="lastname" length="6" order="2" padding=""></tag>
<tag name="date" length="5" order="3" padding=""></tag>
<tag name="amount" length="16" order="4" padding="0">1000</tag>
</fileheader>
<filetrailer>
<tag name="duration" length="8" order="1" padding=" "></tag>
<tag name="count" length="6" order="2" padding=""></tag>
<tag name="date" length="5" order="3" padding=""></tag>
<tag name="totalAmount" length="16" order="4" padding="0">1000</tag>
</filetrailer>
</format>
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Format {
@XmlElement(name = "fileheader")
private FileHeader fileHeader;
@XmlElement(name = "filetrailer")
private FileTrailer fileTrailer;
// getters setters
}
@XmlAccessorType(XmlAccessType.FIELD)
public class FileHeader {
@XmlElementWrapper
@XmlElement(name="tag")
private Tag[] tags;
// getters setters
}
@XmlAccessorType(XmlAccessType.FIELD)
public class FileTrailer {
@XmlElementWrapper
@XmlElement(name="tag")
private Tag[] tags;
// getters setters
}
@XmlAccessorType(XmlAccessType.FIELD)
public class Tag {
@XmlAttribute
private String name;
@XmlAttribute
private int length;
@XmlAttribute
private int order;
@XmlAttribute
private String padding;
@XmlValue
private String defaultVal;
// getters setters
}
Class Test{
public void loadSettings() {
logger.debug("loadsettings.......");
try {
ClassLoader classLoader = getClass().getClassLoader();
InputStream xmlInputStream = classLoader.getResourceAsStream(FORMAT_FILE);
JAXBContext jaxbContext = null;
jaxbContext = JAXBContext.newInstance(Format.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Format format = (Format) unmarshaller.unmarshal(xmlInputStream);
FileHeader fh = format.getFileHeader();
logger.debug("fh-->>{}",fh);
Tag[] tags=fh.getTags();
logger.debug("printing tags ->{}",tags);
}catch (Exception e) {
logger.error("Error ", e);
}
}
}
当我调用loadSetting方法时,标记列表的值未打印。 注解似乎有问题或我的代码有任何其他问题
我的输出
fh->> com.silverleap.cbsl.settlement.config.FileHeader@684c28bb
打印标签-> {}
答案 0 :(得分:0)
成功
@XmlElement(name = "tag")
private List<Tag> tags;