2

我正在尝试将具有表名、行数和列列表的表 bean 输出到 XML。如果我将它们注释为属性,它们会显示:所以这个定义:

@XmlRootElement(name = "table")
public class Table {

    private String tableName;
    private int rowCount;
    private List<Column> columnList;

    @XmlAttribute(name = "name")
    public String getTableName() {
        return tableName;
    }

    @XmlAttribute(name = "rowCount")
    public int getRowCount() {
        return rowCount;
    }

    @XmlElement(name = "column")
    public List<Column> getColumnList() {
        return columnList;
    }

}

输出这个:

    <tables>
     <table name="GGS_MARKER" rowCount="19190">
     <column>
      <columnName>MARKER_TEXT</columnName>
      <datatype>VARCHAR2</datatype>
      <length>4000.0</length>
     </column>
...

但是,如果我用@XmlElement 更改@XmlAttribute,它只会显示:

    <tables>
     <table>
     <column>
      <columnName>MARKER_TEXT</columnName>
      <datatype>VARCHAR2</datatype>
      <length>4000.0</length>
     </column>
...

我应该在课堂上放什么来获得“名称”和“行数”作为元素?

4

1 回答 1

0

在您的示例中,您需要做的就是更改@XmlAttribute@XmlElement. 如果像在您的帖子中那样,您只有get方法而不是set方法,则需要显式添加@XmlElement注释,因为在此用例中不会应用默认注释(默认情况下,假定所有未映射的属性都有@XmlElement注释)。

桌子

package forum10794522;

import java.util.*;
import javax.xml.bind.annotation.*;

@XmlRootElement(name = "table")
public class Table {

    static Table EXAMPLE_TABLE;
    static {
        EXAMPLE_TABLE = new Table();
        EXAMPLE_TABLE.tableName = "GGS_MARKER";
        EXAMPLE_TABLE.rowCount = 19190;
        List<Column> columns = new ArrayList<Column>(2);
        columns.add(new Column());
        columns.add(new Column());
        EXAMPLE_TABLE.columnList = columns;
    }

    private String tableName;
    private int rowCount;
    private List<Column> columnList;

    @XmlElement(name = "name")
    public String getTableName() {
        return tableName;
    }

    @XmlElement(name = "rowCount")
    public int getRowCount() {
        return rowCount;
    }

    @XmlElement(name = "column")
    public List<Column> getColumnList() {
        return columnList;
    }

}

演示

package forum10794522;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Table.class);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(Table.EXAMPLE_TABLE, System.out);
    }

}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<table>
    <column/>
    <column/>
    <rowCount>19190</rowCount>
    <name>GGS_MARKER</name>
</table>
于 2012-05-29T09:55:11.237 回答