user3201607
user3201607

Reputation: 79

creating xml file in java using jaxb

i want to create xml file in java with following format.

<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. how to do this.

Upvotes: 0

Views: 259

Answers (1)

laune
laune

Reputation: 31290

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:

@XmlElement
TableType table;

It's usually much easier to define an XML schema and run xjc to generate the classes.

Upvotes: 1

Related Questions