Can JAXB get XML comments when unmarshalling?

吃可爱长大的小学妹 提交于 2019-12-24 03:52:33

问题


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();
}


来源:https://stackoverflow.com/questions/17831304/can-jaxb-get-xml-comments-when-unmarshalling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!