JAXB为简单数据类型向XmlElement添加属性 [英] JAXB Adding attributes to a XmlElement for simple data types

查看:442
本文介绍了JAXB为简单数据类型向XmlElement添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在从JavaBeans编组时使用JAXB向Xml Elements添加一些属性。 Xml元素是简单的数据类型,如String。所以我不想创建新的类。例如,期望的输出将是:

I want to add some attributes to Xml Elements using JAXB when marshalling from JavaBeans. The Xml Elements are simple data types like String. So I do not want to create new Classes. For example, a desired output would be:

<notifications>
<date>04/20/2011</date>
<subject creditcard_num="22678" checknum="8904">Credit Card Charge Back</subject>
<body payment_amount="34.00" return_status="charged back">some text</body>
</notifications

我不想将主题和正文定义为单独的类。

I do not want to define subject and body as separate classes.

-Anand

推荐答案

你可以用 EclipseLink JAXB(MOXy)的@XmlPath注释解决了这个问题(我是MOXy技术主管):

You could use EclipseLink JAXB (MOXy)'s @XmlPath annotation to solve this problem (I'm the MOXy tech lead):

通知

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Notifications {

    private String date;

    @XmlPath("subject/@creditcard_num")
    private String creditcardNum;

    @XmlPath("subject/@checknum")
    private String checknum;

    private String subject;

    @XmlPath("body/@payment_amount")
    private String paymentAmount;

    @XmlPath("body/@return_status")
    private String returnStatus;

    private String body;

}

jaxb.properties

要将MOXy用作JAXB实现,您需要将名为jaxb.properties的文件放在与模型类相同的包中,并带有以下条目:

To use MOXy as your JAXB implementation you need to put a file named jaxb.properties in the same package as your model classes with the following entry:

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

演示

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Notifications.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Notifications notifications = (Notifications) unmarshaller.unmarshal(new File("input.xml"));

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(notifications, System.out);
    }

}

更多信息:

  • http://bdoughan.blogspot.com/2010/07/xpath-based-mapping.html
  • http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html
  • http://bdoughan.blogspot.com/2011/03/map-to-element-based-on-attribute-value.html

这篇关于JAXB为简单数据类型向XmlElement添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆