我现在正在弄清楚JAXB,而且我非常接近我需要的东西。目前我的ArrayList是从数据库查询中填充的,然后编组到一个文件,但问题是我的编组对象没有包装在根节点中。我该怎么做呢?
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>
答案 0 :(得分:2)
使用@XmlElementWrapper(name = "accounts")
如何使用它:
@XmlElementWrapper(name = "bookList")
// XmlElement sets the name of the entities
@XmlElement(name = "book")
private ArrayList<Book> bookList;
答案 1 :(得分:1)
您可以完成目前正在执行的操作,并在编组对象之前将<accounts>
写入FileOutputStream
,然后再将</accounts>
写入。{/ p>
您还可以引入一个新的域对象来保存列表。
@XmlRootElememnt
@XmlAccessorType(XmlAccessType.FIELD)
public class Accounts {
@XmlElement(name="account")
List<Account> accounts;
}