2013-03-01 41 views
4

我正在搞清楚JAXB,我非常接近我需要的東西。目前我的ArrayList是從一個數據庫查詢填充,然後編組到一個文件,但問題是我編組的對象沒有包裝在一個根節點。我會如何去做這件事?將多個JAXB元素片段組合成一個根節點?

try //Java reflection 
{ 
    Class<?> myClass = Class.forName(command); // get the class named after their input 
    JAXBContext jaxbContext = JAXBContext.newInstance(myClass); 
    Marshaller marshaller = jaxbContext.createMarshaller(); 
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); 
    ArrayList<JAXBElement> listOfJAXBElements = getJAXBElementList(myClass); 
    FileOutputStream fileOutput = new FileOutputStream(command + ".xml", true); 
    for(JAXBElement currentElement: listOfJAXBElements) 
    { 
     marshaller.marshal(currentElement, fileOutput); 
    } 
    fileOutput.close(); 
} 
catch (IOException | NullPointerException | ClassNotFoundException| JAXBException| SecurityException | IllegalArgumentException e) { } 

這裏的賬戶類:

@XmlRootElement(name="accounts") 
@Entity 
@Table(name="Account") 
public class account implements Serializable 
{ 
     ... 
} 

這裏是我的輸出:

<class account> 
    <accountNumber>A101</accountNumber> 
    <balance>500.0</balance> 
    <branchName>Downtown</branchName> 
</class account> 

<class account> 
    <accountNumber>A102</accountNumber> 
    <balance>400.0</balance> 
    <branchName>Perryridge</branchName> 
</class account> 

我想有:

<accounts> 
    <class account> 
     <accountNumber>A101</accountNumber> 
     <balance>500.0</balance> 
     <branchName>Downtown</branchName> 
    </class account> 

    <class account> 
     <accountNumber>A102</accountNumber> 
     <balance>400.0</balance> 
     <branchName>Perryridge</branchName> 
    </class account> 
</accounts> 

編輯1:編組對象的一種一次產生:

<accounts> 
    <accountNumber>A101</accountNumber> 
    <balance>500.0</balance> 
    <branchName>Downtown</branchName> 
</accounts> 

<accounts> 
    <accountNumber>A102</accountNumber> 
    <balance>400.0</balance> 
    <branchName>Perryridge</branchName> 
</accounts> 

回答

1

你可以做的正是目前你正在做什麼,除了寫<accounts>FileOutputStream你面前編組後的物體和</accounts>

您還可以引入一個新的域對象來保存列表。

@XmlRootElememnt 
@XmlAccessorType(XmlAccessType.FIELD) 
public class Accounts { 

    @XmlElement(name="account") 
    List<Account> accounts; 

} 
2

使用@XmlElementWrapper(name = "accounts")

More on XMLElementWrapper註釋

如何使用它:

@XmlElementWrapper(name = "bookList") 
    // XmlElement sets the name of the entities 
    @XmlElement(name = "book") 
    private ArrayList<Book> bookList; 
+0

這給了我:XmlElementWrapper無法解析到類型 – anon58192932 2013-03-01 08:28:05

+2

是不可能的。你確定? – 2013-03-01 08:32:04

+0

由於Eclipse無法找到導入,因此手動導入它。我現在得到了:註釋@XmlElementWrapper不允許用於此位置 – anon58192932 2013-03-01 08:32:47