在列表<x> </x>的编组中排除外部节点

时间:2012-11-09 10:08:40

标签: jaxb

public class Group {
    //many other fields
    public List<Person> persons;
}

public class Person {
    public String name; ...
}

当我想到marhsal时,我想得到一堆Person节点:

<person>
    <name>..</name>
</person>
<person>
    <name>..</name>
</person>

而不是:(人员节点作为子节点的人员节点)

<persons>
    <person>
      <name>..</name>
    </person>
    <person>
      <name>..</name>
    </person>
<persons>

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

<强>更新

如果您将persons称为分组元素而不是根元素,则JAXB (JSR-222)实现默认情况下不会添加一个元素。

组(没有分组元素)

package forum13305973;

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class Group {
    //many other fields
    @XmlElement(name="person")
    public List<Person> persons = new ArrayList<Person>();
}

<强>人

package forum13305973;

public class Person {
    public String name;
}

<强>演示

package forum13305973;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Group.class);

        Group group = new Group();

        Person person1 = new Person();
        person1.name = "Jane";
        group.persons.add(person1);

        Person person2 = new Person();
        person2.name = "John";
        group.persons.add(person2);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(group, System.out);
    }

}

<强>输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<group>
    <person>
        <name>Jane</name>
    </person>
    <person>
        <name>John</name>
    </person>
</group>

组(使用分组元素)

您需要添加@XmlElementWrapper注释才能获得分组元素

package forum13305973;

import java.util.*;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Group {
    //many other fields
    @XmlElementWrapper
    @XmlElement(name="person")
    public List<Person> persons = new ArrayList<Person>();
}

输出(使用分组元素)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<group>
    <persons>
        <person>
            <name>Jane</name>
        </person>
        <person>
            <name>John</name>
        </person>
    </persons>
</group>

原始回答

您可以执行以下操作:

    JAXBContext jc = JAXBContext.newInstance(Person.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // format output
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // remove header

    for(Person person : group.persons) {
        marshaller.marshal(person, System.out);
    }