简体   繁体   English

使用jaxb在Java中创建xml文件

[英]creating xml file in java using jaxb

i want to create xml file in java with following format. 我想用以下格式在Java中创建xml文件。

<xml>
<title>title</title>
<table>
<tr>
<td>
data
</td>
<td>
data
</td>
</tr>
</table>
</xml>

by using the following code i am getting output like. 通过使用以下代码,我得到类似的输出。

<xml>
<description>desc</description>
<keywords>key</keywords>
<linktext>alt</linktext>
<table>table</table>
<td>td</td>
<title>title</title>
<tr>tr</tr>
</xml>


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Xml {

String title,desc,key,link,table,tr,td;

public String getTitle() {
    return title;
}

@XmlElement
public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return desc;
}

@XmlElement
public void setDescription(String desc) {
    this.desc = desc;
}

public String getKeywords() {
    return key;
}

@XmlElement
public void setKeywords(String key) {
    this.key = key;
}

public String getLinktext() {
    return link;
}

@XmlElement
public void setLinktext(String link) {
    this.link = link;
}

public String getTable() {
    return table;
}

@XmlElement
public void setTable(String table) {
    this.table = table;
}

public String getTr() {
    return tr;
}

@XmlElement
public void setTr(String tr) {
    this.tr = tr;
}
public String getTd() {
    return td;
}

@XmlElement
public void setTd(String td) {
    this.td = td;
}


}

jaxbMarshaller.marshal(xml, file);
jaxbMarshaller.marshal(xml, System.out);

but the above code giving output like this. 但是上面的代码给出了这样的输出。 but how to create child node after root node. 但是如何在根节点之后创建子节点。 means in xml tag only i want to create table as child and under the table node i want to create a row as child node to table node. 意味着在xml标记中,仅我想将表创建为子节点,并且在表节点下创建一个行作为子节点到表节点。 how to do this. 这个怎么做。

Define a 定义一个

@XmlType
class TableType {
    @XmlElement(
    RowType tr;
    // ...
}

and a 和一个

@XmlType
class RowType {
    @XmlElement
    ArrayList<String> td;
    // ...
}

and in class Xml, remove what is now in TableType and RowType, and change: 在Xml类中,删除TableType和RowType中的内容,然后更改:

@XmlElement
TableType table;

It's usually much easier to define an XML schema and run xjc to generate the classes. 通常,定义XML模式并运行xjc来生成类要容易得多。

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

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