简体   繁体   English

如何在JAXB中封送具有不同值的多组对象?

[英]How do you Marshal multiple sets of objects with different values in JAXB?

I'm trying to Marshal out tags in which the tags keep changing. 我正在尝试封送标记不断变化的标记。 I keep on overwriting the object values and end up with the same values for the tags when I Marshal. 编组时,我会继续覆盖对象值,并最终获得与标签相同的值。

Desired output: 所需的输出:

<bookshelf>
  <shelfnumber> 001 </shelfnumber>
  <shelfowner> John Snow </shelfowner>
     <book>
        <Author>Ned Stark</Author>
        <Chapters>24</Chapters>
               <Chapter1>.......</Chapter1>
               <Chapter2>.......</Chapter2>
     </book>
     <book>

        <Author>Rob Stark</Author>
        <Chapters>24</Chapters>
               <Chapter1>.......</Chapter1>
               <Chapter2>.......</Chapter2>
     </book>
     <magazine>
        <Author>Tyrion Lannister</Author>
        <Pages>24</Pages>
               <Page1>.......</Page1>
               <Page2>.......</Page2>
     </magazine>    
</bookshelf>

I have a switch statement creating objects while iterating through an arraylist containing the extracted value from the database. 我有一个switch语句在遍历包含从数据库中提取的值的arraylist时创建对象。 I end up overwriting the last object so I am looking for a way to save a set of objects which are populated over each pass of my iterator. 我最终覆盖了最后一个对象,因此我正在寻找一种方法来保存在迭代器的每个遍历中填充的一组对象。

public class TagFactory {
/*
 * Creates an arraylist from which to read the values and populate the tags
 */
private ArrayList<Data> Values;

public TagFactory(ArrayList<Data> values) {
    Values = values;

}

/*
 * Populates the Tran tags for the output based on the values in the Vales
 * arraylist. Uses the index of each cell to match up with the corresponding
 * tags
 */
public Tran TagPopulator() {

    BookShelf bookshelf = new BookShelf();
    Magazine mag = new Magazine();
    Book book = new book();
    Page page = new Page();
    Chapter chapter = new Chapter();


    /*
     * Create iterator and iterate though the extracted data arraylist
     */

    /*
     * Static Fields constructors
     */
    bookshelf.setNumber(BigInteger.valueOf(6));
    bookshelf.setAuthor("John Snow");
    ...

    Iterator<Data> ValuesIt = Values.iterator();

    boolean Endofchapter = false;
    boolean Endofpage = false;

    while (ValuesIt.hasNext()) {

        /*
         * Data object to hold the values
         */
        Data data = ValuesIt.next();

        /*
         * Select the appropriate class object constructor based on the
         * index of the cell This index was previously matched up in
         * HeaderValues and is used for a reference Type modification was
         * done for each of the constructor's requirements.
         */


        switch (data.getcellIndex()) {

        // Book->Author
        case 0:
            book.setAuthor(data.getcellValue());

            break;

        // Book->Chapter-> Chap #
        case 1:
            Chapter.add(data.getcellValue());
            ...
            Endofchapter = true;

            break;

        // Mag -> Author
        case 2:
            mag.setAuthor(data.getcellValue());
            break;

        // Mag->Page->Page#
        case 3:
            /*
             * Page object created and modified
             */
            page.setnum(data.getcellValue());

            Endofpage = true;
            break;

        ...
    if(Endofpage){
        mag.add(page);
    }
    if(Endofchapter){
        book.add(chapter);
    }
    bookshelf.add(mag);
    bookshelf.add(book)
...

I am marshaling after the loop has completed. 循环完成后,我正在编组。

Added the Marshaling function 添加了封送处理功能

 public class XMLWriter {

    private String FileOutput;
    private Tran Transaction;
    ...

    public void FileOut () {
        try {
            /*
             * Marshal the classes into and XML output
             */
             File file = new File(FileOutput);
             JAXBContext JC = JAXBContext.newInstance(Tran.class);
             Marshaller JCMarshaller = JC.createMarshaller();

             JCMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

             JCMarshaller.marshal(Transaction, file);
             JCMarshaller.marshal(Transaction, System.out);

         } catch (JAXBException e) {
             e.printStackTrace();
         } 
    }
}

Added the call to the class for writing the XML. 将调用添加到用于编写XML的类。

XMLWriter output = new XMLWriter(outputFilename, newBookshelf.TagPopulator());
    output.FileOut();

All the objects Except the XMLWriter and TagFactory were produced by JAXB from a schema. 除XMLWriter和TagFactory之外的所有对象均由JAXB通过模式生成。

As we weren't shown the XML schema, the code below may not be an exact fit. 由于我们没有显示XML模式,因此下面的代码可能不完全适合。 It does, however, produce valid XML according to the XML sample. 但是,它确实会根据XML示例生成有效的XML。 The List is replaced by a Scanner, reading from a text file. 列表由扫描仪代替,从文本文件读取。 The intent of your while/switch isn't quite clear to me. 您对while / switch的意图对我不太清楚。 There's no way I can imagine how these add() calls at the end might work correctly. 我无法想象最后的这些add()调用可能如何正常工作。

Note that it is not necessary to complete an object representing an element in the DOM tree before it is inserted into its parent. 请注意,在将DOM树中的元素插入其父级之前,无需完成表示该元素的对象。 For repeated additions, keep a reference to the latest/current book or magazine. 要重复添加,请保留对最新/当前书籍或杂志的引用。

There may be another way to determine the number of chapters and pages. 可能还有另一种方法来确定章节和页面的数量。 I'm completely at a loss what should happen within a chapter or page. 我完全不知道在章节或页面中应该发生什么。

    BookShelf bookshelf = new BookShelf();
    bookshelf.setShelfnumber( "001" );
    bookshelf.setShelfowner( "John Doe" );

    File f = new File( "data.txt" );
    Scanner scanner = new Scanner( f );
    Book book = null;
    Magazine magazine = null;
    int chapters = 0;
    int pages = 0;
    while( scanner.hasNext() ){
        int cellid = scanner.nextInt();
        switch(cellid){
        case 0:
            book = new Book();
            bookshelf.getBookOrMagazine().add( book );
            book.setAuthor( scanner.nextLine() );
            chapters = 0;
            break;
        case 1:
            Chapter chapter = new Chapter();
            book.getChapter().add( chapter );
            chapter.setNumber( scanner.nextInt() );
            book.setChapters( ++chapters );
            break;
        case 2:
            magazine = new Magazine();
            bookshelf.getBookOrMagazine().add( magazine );
            magazine.setAuthor( scanner.nextLine() );
            pages = 0;
            break;
        case 3:
            Page page = new Page();
            magazine.getPage().add( page );
            page.setNumber( scanner.nextInt() );
            magazine.setPages( ++pages );
            break;
        }
    }

The XML schema file I used: 我使用的XML模式文件:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
        version="2.0">
<xs:element name="bookshelf" type="BookShelf"/>
<xs:complexType name="BookShelf">
  <xs:sequence>
    <xs:element name="shelfnumber" type="xs:string"/>
    <xs:element name="shelfowner"  type="xs:string"/>
    <xs:choice maxOccurs="unbounded">
      <xs:element name="book"     type="Book"/>
      <xs:element name="magazine" type="Magazine"/>
    </xs:choice>
  </xs:sequence>
</xs:complexType>
<xs:complexType name="Book">
  <xs:sequence>
    <xs:element name="Author"   type="xs:string"/>
    <xs:element name="Chapters" type="xs:int"/>
    <xs:element name="chapter"  type="Chapter" maxOccurs="unbounded"/>
  </xs:sequence>
</xs:complexType>
<xs:complexType name="Magazine">
  <xs:sequence>
    <xs:element name="Author" type="xs:string"/>
    <xs:element name="Pages"  type="xs:int"/>
    <xs:element name="page"   type="Page" maxOccurs="unbounded"/>
  </xs:sequence>
</xs:complexType>
<xs:complexType name="Chapter">
  <xs:sequence>
    <xs:element name="number" type="xs:int"/>
  </xs:sequence>
</xs:complexType>
<xs:complexType name="Page">
  <xs:sequence>
    <xs:element name="number" type="xs:int"/>
  </xs:sequence>
</xs:complexType>
</xs:schema>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM