I would like to setup a JAXB-annotated Java class to generate some XML in the following format:
我想设置一个带JAXB注释的Java类,以下列格式生成一些XML:
<page refId="0001">
<title>The title of my page</title>
</page>
The "refId" field is optional, so I'd like to use Guava's Optional construct to reference the string in memory. I see Using generic @XmlJavaTypeAdapter to unmarshal wrapped in Guava's Optional, which gives a thorough example if you're using an element (even if that wasn't the original question), but how would you set up the annotations for an XML attribute?
“refId”字段是可选的,所以我想使用Guava的Optional构造来引用内存中的字符串。我看到使用泛型@XmlJavaTypeAdapter解压缩包装在Guava的Optional中,如果您使用的是元素(即使这不是原始问题),它会提供一个完整的示例,但是您如何设置XML属性的注释?
Here's what I have so far:
这是我到目前为止所拥有的:
@XmlRootElement(name="page")
public final class Page {
@XmlAttribute
@XmlJavaTypeAdapter(OptionalAdapter.class)
private Optional<String> refId;
@XmlElement
private String title;
... getters/setters, default constructor, etc.
}
And OptionalAdapter is a simple XmlAdapter:
而OptionalAdapter是一个简单的XmlAdapter:
public class OptionalAdapter<T> extends XmlAdapter<T, Optional<T>> {
@Override
public Optional<T> unmarshal(T v) throws Exception {
return Optional.fromNullable(v);
}
@Override
public T marshal(Optional<T> v) throws Exception {
if (v == null || !v.isPresent()) {
return null;
} else {
return v.get();
}
}
}
When I try to load up a unit test against the above code, it fails instantly during initialization, but if I change the annotation to @XmlElement, the test will run and pass, but obviously sets the refId as a child element instead of an attribute.
当我尝试针对上面的代码加载单元测试时,它在初始化期间立即失败,但是如果我将注释更改为@XmlElement,测试将运行并通过,但显然将refId设置为子元素而不是属性。
Thanks in advance!
提前致谢!
1 个解决方案
#1
5
Xml-attribute can have only simple type (like String
, Integer
etc.), so you cann't use OptionalAdapter<T>
.
If your field has type String
then adapter should have type OptionalAdapter<String>
.
You can do in next way:
- create additional class, and use is as XmlAdapter
Xml属性只能有简单类型(如String,Integer等),因此不能使用OptionalAdapter
public final class StringOptionalAdapter extends OptionalAdapter<String>
{
}
Page.java
Page.java
@XmlAttribute
@XmlJavaTypeAdapter(StringOptionalAdapter.class)
private Optional<String> refId;
#1
5
Xml-attribute can have only simple type (like String
, Integer
etc.), so you cann't use OptionalAdapter<T>
.
If your field has type String
then adapter should have type OptionalAdapter<String>
.
You can do in next way:
- create additional class, and use is as XmlAdapter
Xml属性只能有简单类型(如String,Integer等),因此不能使用OptionalAdapter
public final class StringOptionalAdapter extends OptionalAdapter<String>
{
}
Page.java
Page.java
@XmlAttribute
@XmlJavaTypeAdapter(StringOptionalAdapter.class)
private Optional<String> refId;