解组时JAXB可以获得XML注释吗?

时间:2013-07-24 10:24:37

标签: xml jaxb comments unmarshalling

我使用JAXB解析XML,但XML在结尾处有注释,我想要解析它来存储它。

XML:

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

我需要获得评论的字符串。
JAXB有功能给我评论吗?

2 个答案:

答案 0 :(得分:0)

Jaxb活页夹允许您阅读Blaise Doughan在此处记录的评论 http://bdoughan.blogspot.com/2010/09/jaxb-xml-infoset-preservation.html

要获得特定元素下方的评论,请使用例如

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

答案 1 :(得分:-1)

您可以将JAXB与StAX结合使用来访问尾随注释。

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

}