Can JAXB get XML comments when unmarshalling?

2019-08-09 06:59发布

问题:

Im parsing a XML with JAXB but the XML have a comment at end and i want parser it to store it.

Xml:

<xml>...</xml>
<!--RUID: [UmFuZG9tSVYkc2RlIyh9YUMeu8mgftUJQvv83JiDhiMR==] -->

I need to get the String of the comment.
JAXB have a function to give me the comment ?

回答1:

You could use JAXB in combination with StAX to get access to the trailing comment.

import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        XMLInputFactory xif = XMLInputFactory.newFactory();
        StreamSource source = new StreamSource("src/forum17831304/input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(source);

        JAXBContext jc = JAXBContext.newInstance(Xml.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Xml xml = (Xml) unmarshaller.unmarshal(xsr);

        while(xsr.hasNext()) {
            if(xsr.getEventType() == XMLStreamConstants.COMMENT) {
                System.out.println(xsr.getText());
            }
            xsr.next();
        }
    }

}


回答2:

The Jaxb binder allows you to read comments, as documented by Blaise Doughan here http://bdoughan.blogspot.com/2010/09/jaxb-xml-infoset-preservation.html.

To get to a comment below a specific element, use e.g.

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(yourFile);
JAXBContext jc = JAXBContext.newInstance(YourType.class.getPackage().getName());
Binder<Node> binder = jc.createBinder();
JAXBElement<YourType> yourWrapper = binder.unmarshal(document, YourType.class);
YourType rootElement = yourWrapper.getValue();

// Get comment below root node
Node domNode = binder.getXMLNode(rootElement);
Node nextNode = domNode.getNextSibling();
if (nextNode.getNodeType() == Node.COMMENT_NODE) {
    comment = nextNode.getTextContent();
}