Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...