我现在正在研究 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>