developer tip

JAXB : 목록에서 객체를 마샬링하는 방법?

optionbox 2020. 12. 1. 07:56
반응형

JAXB : 목록에서 객체를 마샬링하는 방법?


아마도 어리석은 질문 일 것 입니다. XML 파일에 마샬링하려는 List유형 <Data>이 있습니다. 이것은 Database포함하는 내 수업 입니다 ArrayList...

@XmlRootElement
public class Database
{
    List<Data> records = new ArrayList<Data>();

    public List<Data> getRecords()                   { return records; }
    public void       setRecords(List<Data> records) { this.records = records; }
}

... 그리고 이것은 클래스 데이터입니다.

// @XmlRootElement
public class Data 
{
    String name;
    String address;

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

    public String getAddress()               { return address;         }
    public void   setAddress(String address) { this.address = address; }
}

다음 테스트 클래스 사용 ...

public class Test
{
    public static void main(String args[]) throws Exception
    {
        Data data1 = new Data();
             data1.setName("Peter");
             data1.setAddress("Cologne");

        Data data2 = new Data();
             data2.setName("Mary");
             data2.setAddress("Hamburg");

        Database database = new Database();
                 database.getRecords().add(data1);
                 database.getRecords().add(data2);

        JAXBContext context = JAXBContext.newInstance(Database.class);
        Marshaller marshaller = context.createMarshaller();
                   marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                   marshaller.marshal(database, new FileWriter("test.xml"));       
    }
}

... 결과를 얻었습니다.

<database>
    <records>
        <address>Cologne</address>
        <name>Peter</name>
    </records>
    <records>
        <address>Hamburg</address>
        <name>Mary</name>
    </records>
</database>

그러나 그것은 내가 예상했던 것이 아닙니다. 즉, <Data>객체에 대한 모든 태그 가 없습니다. 다음 구조로 데이터를 내보내는 방법을 찾고 있지만이를 달성하는 방법을 모르겠습니다.

<database>
    <records>
        <data>
            <address>Cologne</address>
            <name>Peter</name>
        </data>
        <data>
            <address>Hamburg</address>
            <name>Mary</name>
        </data>
    </records>
</database>

추가 질문 : 주석 사용 하지 않고 문제를 처리 하려면 중개 클래스를 도입 할 수 있습니다.@XmlElementWrapper@XmlElement

public class Records
{
    List<Data> data = new ArrayList<Data>();

    public List<Data> getData()                { return data; }
    public void       setData(List<Data> data) { this.data = data; }
}

수정 된 기본 클래스에서 사용

@XmlRootElement
public class Database
{
    Records records = new Records();

    public Records getRecords()                { return records; }
    public void    setRecords(Records records) { this.records = records; }
}

약간 수정 된 Test클래스 :

...
Database database = new Database();
database.getRecords().getData().add(data1);
database.getRecords().getData().add(data2);
...

결과는 다음과 같습니다.

<database>
    <records>
        <data>
            <address>Cologne</address>
            <name>Peter</name>
        </data>
        <data>
            <address>Hamburg</address>
            <name>Mary</name>
        </data>
    </records>
</database>

Is this the recommended way to create a Java class structure according to the XML file structure above?


On the records property add:

@XmlElementWrapper(name="records")
@XmlElement(name="data")

For more information on JAXB and collection properties see:


This is in response to your second question disquised an answer:

Both approaches will generate the same XML. My recommendation is go with the model that is best for your application. For me that is generally using @XmlElementWrapper/@XmlElement. Since "records" is just there to organize the "data" elements it doesn't really deserve its own class.

I lead the MOXy JAXB implementation and we offer an XPath-based mapping extension to go beyond what is capable with @XmlElementWrapper:


In response to your second question:

Is this the recommended way to create a Java class structure
according to the XML file structure above?

Technically speaking, introducing an extra Records class to solve your JAXB issue is unnecessary and redundant work, because JAXB does not need it. The @XmlElementWrapper and @XmlElement name property have been designed to solve your issue.

From your comments to Blaise's answer, I maintain a tutorial with operational examples explaining how do deal with generic classes such as List, etc.. when unmarshalling.

참고URL : https://stackoverflow.com/questions/3683598/jaxb-how-to-marshal-objects-in-lists

반응형