JAXB:将 Javabean 对象转换为 XML,所有属性作为 XML 属性而不是 XML 元素(节点)
目前我正在将对象转换为 XML,我注意到所有对象属性都被列为 XML 元素(节点),除非您在特定的 getter 或设置上使用 @XmlAttribute
只是想知道是否有一种方法可以自动将所有对象属性转换为 XML 属性在 JAXB 中。
示例代码:
JAXBContext jc = JAXBContext.newInstance( foo.class );
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(Marshaller.JAXB_FRAGMENT, true);
Foo foo = new foo();
foo.setType("type");
foo.setValue("value");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
m.marshal(foo, baos);
Currently I'm working on converting object to XML, I notice all object properties are listed as XML elements (node) unless you use @XmlAttribute on a particular getter or setting
Just wondering is there a way to automatically convert all object properties as XML attributes in JAXB.
Sample Code:
JAXBContext jc = JAXBContext.newInstance( foo.class );
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(Marshaller.JAXB_FRAGMENT, true);
Foo foo = new foo();
foo.setType("type");
foo.setValue("value");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
m.marshal(foo, baos);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
注意:我是EclipseLink JAXB (MOXy) 的领导者和 JAXB 的成员(JSR-222)专家组。
当前没有一种方法可以配置默认情况下简单属性应映射到 XML 属性。已向 MOXy 提交以下增强请求以添加此行为。
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
There currently isn't a way to configure that by default simple properties should map to XML attributes. The following enhancement request has been filed for MOXy to add this behaviour.
您是否尝试过在类顶层使用@XmlRootElement?
have you tried using @XmlRootElement on the class top level?
如果您将 JAXB 用于复杂的模式,最好在
XSD
中定义结构:可以使用
jaxb-xjc
将其编译为.java
文件,并且您将定义 xsd:attributes 作为 Java 中的属性。If you are using JAXB for a complex schemata, it's a good idea to define the structure in a
XSD
:This can be compiled with
jaxb-xjc
to.java
files and you will have the defined xsd:attributes as attributes in Java.