gpt4 book ai didi

java - 如何使用 JAXB 将 SimpleStringProperty 对象转换为 XML

转载 作者:行者123 更新时间:2023-12-01 09:07:58 25 4
gpt4 key购买 nike

我使用 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 正常提取 XMLXML 如下所示:

<sectionList>
<name>Section 1</name>
<themes>
<name>Theme 1</name>
</themes>
</sectionList>

但是当我使用 private SimpleStringProperty name, description; return null;和 XML 看起来像这样:

<sectionList>
<name/>
<themes>
<name/>
</themes>
</sectionList>\

我必须在项目中使用SimpleStringProperty。怎么了?如何将 SimpleStringProperty 提取到 XML

最佳答案

您的方法定义不正确。查看任何 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 参数。

关于java - 如何使用 JAXB 将 SimpleStringProperty 对象转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41101937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com