我正在搞清楚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>
這給了我:XmlElementWrapper無法解析到類型 – anon58192932 2013-03-01 08:28:05
是不可能的。你確定? – 2013-03-01 08:32:04
由於Eclipse無法找到導入,因此手動導入它。我現在得到了:註釋@XmlElementWrapper不允許用於此位置 – anon58192932 2013-03-01 08:32:47