首页 > 解决方案 > 使用 StaX 忽略评论

问题描述

使用以下代码,我成功读取了 XML 文件。但是,当注释出现在节点中间时,阅读器将丢弃节点的其余部分。例如:

<text>thisismy<!--comment-->document</text>

将导致返回字符串“thisismy”,仅此而已。

我之前遇到过类似的问题,当我遇到特殊字符时,我将&其设置XMLInputFactoryisCoalescing=true修复。我猜我遇到了一个相关的功能。

我需要能够优雅地处理这些文件。谁能建议我如何解决这种中断?

try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty("javax.xml.stream.isCoalescing", true);
        XMLEventReader eventReader =
                factory.createXMLEventReader(new FileReader(fileName));

        while(eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();

            switch(event.getEventType()) {

                case XMLStreamConstants.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String qName = startElement.getName().getLocalPart();

                    if (qName.equalsIgnoreCase("page")) {
                        page = new DocumentPage();
                        Iterator<Attribute> attributes = startElement.getAttributes();
                        while(attributes.hasNext())
                        {
                            Attribute attribute = attributes.next();
                            switch (attribute.getName().toString().toLowerCase()) {
                                case "index" :
                                    pageIndex = attribute.getValue();
                                    page.setPageIndex(pageIndex);
                                    break;

标签: xmlstaxxml-comments

解决方案


推荐阅读