2012-05-29 107 views
2

我想输出到XML表的表名与表名,行数和列的列表。如果我注释它们喜欢的属性,它们显示: 所以这样的定义:元素没有显示使用JAXB

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

但是,如果我改变@XmlAttribute与@XmlElement,它只是显示:

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

我应该怎样在类中放入“name”和“rowcount”作为元素?

+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>