2

我用 JAXB 解析 aXML但最后XML有评论,我希望解析它来存储它。

xml:

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

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

4

2 回答 2

0

Jaxb binder 允许您阅读评论,正如 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();
}
于 2017-06-09T10:21:14.033 回答
-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();
        }
    }

}
于 2013-07-24T13:28:43.620 回答