我使用Jackson XML映射程序将对象转换为XML
ArrayList<Person> temp = new ArrayList<Person>();
Person a = new Person(12);
temp.add(a);
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(path, temp);Person类如下所示:
public class Person{
private int age;
public Person(int age){
this.age = age
}
}XML看起来像:
<ArrayList>
<item>
<age>12</age>
</item>
</ArrayList>如何重命名"ArrayList“和"item”标记?
发布于 2022-01-18 08:38:25
您可以为Person列表创建一个包装类。
// imports used
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
static class Person {
private int age;
Person() {
}
Person(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@JacksonXmlRootElement(localName = "people")
static class People {
@JacksonXmlProperty(localName = "person")
@JacksonXmlElementWrapper(useWrapping = false)
private List<Person> people = new ArrayList<>();
public List<Person> getPeople() {
return people;
}
public void setPeople(List<Person> people) {
this.people = people;
}
}
public static void main(String[] args) throws IOException {
People people = new People();
Person person = new Person(12);
people.setPeople(List.of(person));
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(new File("people.xml"), people);
}最重要的是:
@JacksonXmlProperty(localName = "person")
@JacksonXmlElementWrapper(useWrapping = false)
private List<Person> people = new ArrayList<>();在类People中,它是您的包装类,在该类中,您说您有一个Person列表,但是您不想用正常的名称包装另一组标记。
另外,当您添加包装类时,生成的xml标记将使用大写的P(即<People>)。
因此,对于这种情况,我们可以在声明类@JacksonXmlRootElement之前添加,这使您可以根据自己的意愿重命名它(我在这里所做的工作只是将xml标记降为<people> )。
由此产生的xml:
<people>
<person>
<age>12</age>
</person>
</people>发布于 2022-09-16 03:17:33
万一有人需要这样的东西..。
<onlinebestellung>
<positionen>
<artikel>
<artikelnummer>articleId</artikelnummer>
<description>"your description here</description>
</artikel>
</positionen>
</onlinebestellung>...you可以用jackson来尝试这一点
@JacksonXmlRootElement(localName = "onlinebestellung")
public class OrderTest {
@JacksonXmlElementWrapper(useWrapping = true, localName = "positionen")
@JacksonXmlProperty(localName = "artikel")
private List<Article> position;
}
public class Article {
private String artikelnummer;
private String description;
}https://stackoverflow.com/questions/70751438
复制相似问题