编程语言
首页 > 编程语言> > java – 需要格式化JAXB输出的帮助

java – 需要格式化JAXB输出的帮助

作者:互联网

我有一些对象让我们说两个,A和B.这些对象来自同一个类.我需要使用JAXB封送这些对象,输出XML应采用以下形式:

<Root>
    <A>
        <ID> an id </ID>
    </A>
    <B>
        <ID> an id </ID>
    </B>
</Root>

<!-- Then all A and B attributes must be listed !-->
<A>
    <ID> an id </ID>
    <attribute1> value </attribute1>
    <attribute2> value </attribute2>
</A>
<B>
    <ID> an id </ID>
    <attribute1> value </attribute1>
    <attribute2> value </attribute2>
</B>

如何在JAXB中生成此格式?任何帮助表示赞赏.

更新:
更具体地说,假设我们有这样的Human类:

@XmlRootElement
public class Human {
    private String name;
    private int age;
    private Integer nationalID;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Integer getNationalID() {
        return nationalID;
    }

    public void setNationalID(Integer nationalID) {
        this.nationalID = nationalID;
    }
}

我们的主要课程是:

public class Main3 {

    public static void main(String[] args) throws JAXBException {
        Human human1 = new Human();
        human1.setName("John");
        human1.setAge(24);
        human1.setNationalID(Integer.valueOf(123456789));

        JAXBContext context = JAXBContext.newInstance(Human.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        StringWriter stringWriter = new StringWriter();

        m.marshal(human1, stringWriter);

        System.out.println(stringWriter.toString());
    }

}

然后输出将是:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<human>
    <age>24</age>
    <name>John</name>
    <nationalID>123456789</nationalID>
</human>

现在我需要输出如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<human>
    <nationalID>123456789</nationalID>
</human>
<human>
    <nationalID>123456789</nationalID>
    <age>24</age>
    <name>John</name>
</human>

这将帮助我绘制一个没有属性的XML对象树(只有ID),然后是树下面的所有定义.这可能使用JAXB或任何其他实现吗?

解决方法:

试试这个:

import java.io.StringWriter;
import javax.xml.bind.Marshaller;

...

Object requestObject = ...  // This is the object that needs to be printed with indentation
Marshaller marshaller = ...
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter stringWriter = new StringWriter();
marshaller.marshal(requestObject, stringWriter);

System.out.println(stringWriter.toString());

标签:java,xml,jaxb2,xml-formatting
来源: https://codeday.me/bug/20190713/1450887.html