3 回答
TA贡献1846条经验 获得超7个赞
使用 JAXB 解组器将 xml 文档转换为 java 对象。首先将 JAXB 依赖项添加到项目的类路径中。了解更多信息
SampleDTO.java
@XmlRootElement
public class SampleDTO {
private String id;
private List<SomeList> someList;
private List<OtherList> otherList;
@XmlElement
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement
public List<SomeList> getSomeList() {
return someList;
}
public void setSomeList(List<SomeList> someList) {
this.someList = someList;
}
@XmlElement
public List<OtherList> getOtherList() {
return otherList;
}
public void setOtherList(List<OtherList> otherList) {
this.otherList = otherList;
}
}
SomeList.java
@XmlRootElement
public class SomeList {
private List<SomeObject> someObject;
@XmlElement
public List<SomeObject> getSomeObject() {
return someObject;
}
public void setSomeObject(List<SomeObject> someObject) {
this.someObject = someObject;
}
}
OtherList.java
@XmlRootElement
public class OtherList {
private List<OtherObject> otherObject;
@XmlElement
public List<OtherObject> getOtherObject() {
return otherObject;
}
public void setOtherObject(List<OtherObject> otherObject) {
this.otherObject = otherObject;
}
}
SomeObject.java
@XmlRootElement
public class SomeObject {
private String amount;
private String id;
private String someDescription;
@XmlElement
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
@XmlElement
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement
public String getSomeDescription() {
return someDescription;
}
public void setSomeDescription(String someDescription) {
this.someDescription = someDescription;
}
}
OtherObject.java
@XmlRootElement
public class OtherObject {
private String flag;
private String id;
private String otherDescription;
@XmlElement
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
@XmlElement
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement
public String getOtherDescription() {
return otherDescription;
}
public void setOtherDescription(String otherDescription) {
this.otherDescription = otherDescription;
}
}
使用 JAXB 解组
public class Main {
public static void main(String[] args) {
try {
File file = new File("file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(SampleDTO.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
SampleDTO sampleDTO= (SampleDTO) jaxbUnmarshaller.unmarshal(file);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
TA贡献1880条经验 获得超4个赞
有许多可用的开源 XML 处理包。我喜欢杰克逊。这是关于 Jackson XML 的 Baeldung 文章的链接
总结是这样的:
将 Jackson 依赖项添加到您的 POM。
创建一个代表您的 xml 结构的对象结构。
创建一个 XmlMapper。
使用 XmlMapper。
TA贡献1966条经验 获得超4个赞
你的 java 类/对象应该至少有这 3 个实例变量:
private int amount
private int id
private String description
然后使用一些 xml 解析库(例如jdom2),并且对于您迭代的每个<someObject>标签,初始化您的类的一个新对象并为其分配从 xml 解析的值(数量/id/描述),并添加每个新创建的对象在列表或数组等中。
添加回答
举报