Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

java - Formatting XML with JAXB

I've been trying to find a similar answered question but I haven't had any luck.

I basically need to read some data off a text file and then marshal it to XML. Normal formatting though, creates

<title></title> 

fields etc. while what I want is every field to have this format:

<field name="title"></field>.

"title" here is just a placeholder, what I want is for the name attribute to have the variable name which it is bound, so

<title> 

becomes

<field name="title">

,

<author> 

becomes

<field name="author"> etc.

I'm guessing it has something to do with the annotations that I'm not getting.

My document class has a simple structure, like

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Document
{
    private Integer id;
    private String content;
    private String title;
    private String author;
    private String b;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Each XML element (not attribute) in JAXB is a Java class. And attribute can be a property. So you have to have something like:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Document
{
   @XmlElement(name = "field")
   private List<Field> field = new ArrayList<>();
}

and

@XmlType()
public class Field
{
   @XmlAttribute(name="name", required="true")
   private String name;

   @XmlValue
   private Object value;

}

Actually private Object value; translates to XML anyType so you will be able to set it to Integer for id, String for content etc.

BTW your current Document class marshalls to XML as

<Document>
      <id></id>
      <content></content>
      <title></title>
      <author></author>
      <b></b>
<Document>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...