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

Categories

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

java - How to instantiate an empty element with JAXB

I use JAXB to create XML messages. The XML I need to create is (for the sake of simplicity):

<request>
  <header/>
</request>

My code looks like this:

import javax.xml.bind.annotation.*;

@XmlRootElement(name = "request")
public class Request {

    private String header;

    @XmlElement(required=true)
    public String getHeader() {
      return header;
    }

    public void setHeader(String header) {
      this.header=header;
    }
}

The problem: the header element is not displayed (header is null). When header is set to an empty string, the following is displayed:

<request>
  <header></header>
</request>

When I use as type Object instead of String, the result is even worse:

<request>
  <header xsi:type="xs:string" 
   xmlns:xs="http://www.w3.org/2001/XMLSchema" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></header>
</request>

BTW: I'm using this code to create the XML string.

Is it possible to get an empty tag?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

In XML, <header/> and <header></header> are the same thing. If you really want the former, then use a prettifier. javax.xml.transform.TransformerFactory.newTransformer() will probably do that for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...