元素未显示使用JAXB

时间:2012-05-29 07:03:53

标签: java jaxb

我正在尝试使用表名,行计数和列列表向XML输出表bean。如果我像属性一样注释它们,它们会显示: 所以这个定义:

@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>
...

我应该在课堂上怎样才能获得&#34; name&#34;和&#34; rowcount&#34;作为元素?

1 个答案:

答案 0 :(得分: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>