如何使用JAXB实例化一个空元素 [英] How to instantiate an empty element with JAXB
问题描述
我使用JAXB来创建XML消息。我需要创建的XML(为了简单起见):
I use JAXB to create XML messages. The XML I need to create is (for the sake of simplicity):
<request>
<header/>
</request>
我的代码如下所示:
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;
}
}
问题:标题
元素未显示(标题为 null
)。当标题设置为空字符串时,将显示以下内容:
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>
当我使用类型对象
而不是 String
,结果更糟:
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:我正在使用此代码用于创建XML字符串。
BTW: I'm using this code to create the XML string.
是否可以获得空标签?
推荐答案
In XML,< header />
和< header>< / header>
是一回事。如果你真的想要前者,那就使用美化剂。 javax.xml.transform.TransformerFactory.newTransformer()
可能会为您做到这一点。
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.
这篇关于如何使用JAXB实例化一个空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!