JAXB能得到XML注释解组时?(Can JAXB get XML comments when un

2019-10-18 09:51发布

林解析XML与JAXB但XML必须在结束评论,我想解析器它来存储它。

XML:

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

我需要注释的字符串。
JAXB有一个函数来给我有何评论?

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

}


Answer 2:

JAXB的粘结剂可以读取评论,布莱斯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();
}


文章来源: Can JAXB get XML comments when unmarshalling?