我必须使用javax.xml.bind.annotation库中的注解用java编写一个配置读取器。问题是我真的不知道如何访问内部节点(在我的例子中是mailconfig)。以下是我的xml文件的格式:
<?xml version="1.0" encoding="UTF-8">
<config>
<avoidanceList>
<avoid> item1 </avoid>
<avoid> item2 </avoid>
</avoidanceList>
<ignoreList>
<ignore> item1 </ignore>
</ignoreList>
<mailConfig>
<from> From </from>
<toList>
<to> To1 </to>
<to> To2 </to>
</toList>
</mailConfig>
</config>
我可以读入avoidancelist和ignorelist,但是我的代码不能读入整个mailconfig。我在某个地方读到有两门课可以解决这个问题,但事实并非如此。这是我的阅读器代码:
@XmlRootElement(name = "config")
public final class Cfg {
private List<String> avoidanceList;
private List<String> ignoreList;
private MailConfig mailConfig;
@XmlElementWrapper(name = "avoidanceList")
@XmlElement(name = "avoid", required = false)
public List<String> getAvoidanceList() {
return avoidanceList;
}
@XmlElementWrapper(name = "ignoreList")
@XmlElement(name = "ignore", required = false)
public List<String> getIgnoreList() {
return ignoreList;
}
@XmlElements({
@XmlElement(name="from", type=String.class),
@XmlElement(name="to", type=String.class)})
public MailConfig getMailConfig() {
return mailConfig;
}
}
这里是mailconfig类:
@XmlRootElement(name = "mailConfig")
public class MailConfig {
private String from;
private List<String> toList;
public MailConfig(String from, List<String> toList) {
this.from = from;
this.toList = toList;
}
@XmlElement(name = "from", required = false)
public String getFrom() {
return from;
}
@XmlElementWrapper(name = "toList")
@XmlElement(name = "to", required = false)
public List<String> getToList() {
return toList;
}
}
这是我第一次用java处理xml文件,所以我知道代码可能完全错了。我还没有找到注解的解决方案,所以如果有人能帮助我,这将是非常好的:)
提前谢谢!
1条答案
按热度按时间unftdfkk1#
试试这个,对我有用: