我使用JAXB( Java Architecture for XML Binding )将Java
对象转换为XML
文件
JAXBContext context = JAXBContext.newInstance(MetaListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Wrapping my data.
MetaListWrapper wrapper = new MetaListWrapper();
wrapper.setTree(sectionList);
// Marshalling and saving XML to the file.
m.marshal(wrapper, file);
这是我的包装:
@XmlRootElement(name = "metadata")
public class MetaListWrapper {
private List<Section> sectionList;
@XmlElement(name = "sectionList")
public List<Section> getTree() {
return sectionList;
}
public void setTree(List<Section> sectionList) {
this.sectionList = sectionList;
}
}
这是Section对象:
public class Section {
List<Theme> themes;
private SimpleStringProperty name, description;
@Override
public String toString() {
return name.toString();
}
public List<Theme> getThemes() {
return themes;
}
public void setThemes(List<Theme> themes) {
this.themes = themes;
}
public SimpleStringProperty getName() {
return name;
}
public void setName(SimpleStringProperty name) {
this.name = name;
}
public SimpleStringProperty getDescription() {
return description;
}
public void setDescription(SimpleStringProperty description) {
this.description = description;
}
}
当我在对象中使用private String name, description;
时(部分和主题)JAXB
正常提取XML
。 XML
看起来像这样:
<sectionList>
<name>Section 1</name>
<themes>
<name>Theme 1</name>
</themes>
</sectionList>
但是当我使用private SimpleStringProperty name, description;
时返回null;和XML
看起来像这样:
<sectionList>
<name/>
<themes>
<name/>
</themes>
</sectionList>\
我必须在项目中使用SimpleStringProperty
。怎么了?如何将SimpleStringProperty
提取到XML
?
答案 0 :(得分:1)
您的方法定义不正确。查看任何JavaFX类的javadoc,您将看到正确的方法。
例如,考虑Circle类:
private final DoubleProperty radius = new SimpleDoubleProperty();
public DoubleProperty radiusProperty() {
return radius;
}
public double getRadius() {
return radius.get();
}
public void setRadius(double value) {
radius.set(value);
}
(以上是简化的近似值,不是从该类的实际来源中获取的。)
在任何情况下,get方法都不应返回Property。在任何情况下,set方法都不应该使用Property参数。