首页 文章

元素未显示使用JAXB

提问于
浏览
2

我试图输出一个表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>
...

我应该在课堂上添加“name”和“rowcount”作为元素?

1 回答

  • 0

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

    Table

    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;
        }
    
    }
    

    Demo

    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);
        }
    
    }
    

    Output

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <table>
        <column/>
        <column/>
        <rowCount>19190</rowCount>
        <name>GGS_MARKER</name>
    </table>
    

相关问题