将多个JAXB元素片段组合到一个根节点中



我现在正在研究JAXB,我非常非常接近我所需要的。目前,我的ArrayList是从DB查询中填充的,然后整理到一个文件中,但问题是我整理的对象没有包装在根节点中。我该怎么做?

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(name = "accounts")

关于XMLElementWrapper注释的更多信息

如何使用:

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

您可以完全执行当前正在执行的操作,此外,在封送对象之前将<accounts>写入FileOutputStream,然后将</accounts>写入。

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

@XmlRootElememnt
@XmlAccessorType(XmlAccessType.FIELD)
public class Accounts {
    @XmlElement(name="account")
    List<Account> accounts;
}

最新更新