4

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

2 回答 2

2

采用@XmlElementWrapper(name = "accounts")

有关 XMLElementWrapper注释的更多信息

如何使用它:

  @XmlElementWrapper(name = "bookList")
  // XmlElement sets the name of the entities
  @XmlElement(name = "book")
  private ArrayList<Book> bookList;
于 2013-03-01T08:26:11.100 回答
1

您可以完全按照您当前正在做的事情做,此外还<accounts>可以FileOutputStream在编组对象之前和</accounts>之后写入。

您还可以引入一个新的域对象来保存列表。

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

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

}
于 2013-03-01T11:02:15.837 回答