我试图将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。
  选择支持的实现
  此方法必须重写此方法。


在那里的任何JAXB实现都实现了getNode(Object)吗?

最佳答案

注意:我领导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 {

}

07-24 14:31