哪个JAXB实现实现了Marshaller.getNode()?

时间:2011-06-06 11:17:43

标签: java xml spring jaxb marshalling

我正在尝试add a comment到JAXB生成的XML @GET结果,这似乎不是一个简单的任务。我正在使用Spring,I don't have direct access to the marshalling and DOM

通过将public void beforeMarshal(Marshaller m)添加到我的@XmlElement,我应该能够使用Marshaller#getNode(Object)访问DOM,从而能够添加评论。

问题是AbstractMarshallerImpl#getNode(Object)

  

默认情况下,getNode方法是   不支持并抛出一个   java.lang.UnsupportedOperationException。   选择支持的实现   此方法必须覆盖此方法。

getNode(Object)是否由任何JAXB实现实现?

1 个答案:

答案 0 :(得分:2)

注意:我领导EclipseLink JAXB (MOXy)并且是JAXB 2(JSR-222)专家组的成员。


MOXy目前不支持可选的getNode方法,请参阅(增强请求https://bugs.eclipse.org/332762)。但是,JAXB的Binder可能对此用例有用:

演示

import javax.xml.bind.Binder;
import javax.xml.bind.JAXBContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class Demo {

    public static void main(String[] args) throws Exception {
        Customer customer = new Customer();
        customer.setName("Jane Doe");

        PhoneNumber homePhoneNumber = new PhoneNumber();
        customer.getPhoneNumbers().add(homePhoneNumber);

        PhoneNumber workPhoneNumber = new PhoneNumber();
        customer.getPhoneNumbers().add(workPhoneNumber);

        JAXBContext jc = JAXBContext.newInstance(Customer.class);

        Binder<Node> binder = jc.createBinder();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();

        binder.marshal(customer, document);
        Node homePhoneNumberElement = binder.getXMLNode(homePhoneNumber);
        Comment comment = document.createComment("My Comment");
        homePhoneNumberElement.appendChild(comment);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(System.out);
        t.transform(source, result);
    }

}

<强>客户

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    private String name;

    private List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement(name="phone-number")
    public List<PhoneNumber> getPhoneNumbers() {
        return phoneNumbers;
    }

    public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }

}

<强> ******中国

public class PhoneNumber {

}