Unable to check CDATA in XML using XMLEventReader in Stax

倖福魔咒の 提交于 2019-12-04 02:16:10

问题


I am unable to check for CDATA in XML and read it using XMLEventReader.

The following is the sample:

 <name>HEADERS</name>
                        <data>
                            <![CDATA[ Sat Nov 19 18:50:15 2016 (1672822) 
]]>
                            <![CDATA[Sat, 19 Nov 2016 18:50:14 -0800 (PST)       
]]>
                        </data>

The XMLEventReader of Stax api which i am using is as follows:

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

        if (event.isCharacters()) {
            System.out.println(event.asCharacters().isCData());
            System.out.println(event.asCharacters().getData());
 }
  }

So,when I read the data tag for characters, I get false for event.asCharacters().isCData(). Would like to know how to check for CDATA in EventReader and get the CDATA as well.


回答1:


Use the following pattern:

  switch (EventType) {
        case XMLStreamConstants.CHARACTERS:
        case XMLStreamConstants.CDATA:
            System.out.println(r.getText());
            break;
        default:
            break;
        }

Complete sample:

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public void readCDATAFromXMLUsingStax() {
    String yourSampleFile = "/path/toYour/sample/file.xml";
    XMLStreamReader r = null;
    try (InputStream in =
            new BufferedInputStream(new FileInputStream(yourSampleFile));) {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        r = factory.createXMLStreamReader(in);
        while (r.hasNext()) {
            switch (r.getEventType()) {
            case XMLStreamConstants.CHARACTERS:
            case XMLStreamConstants.CDATA:
                System.out.println(r.getText());
                break;
            default:
                break;
            }
            r.next();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (r != null) {
            try {
                r.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}

With /path/toYour/sample/file.xml

 <data>
    <![CDATA[ Sat Nov 19 18:50:15 2016 (1672822)]]>
    <![CDATA[Sat, 19 Nov 2016 18:50:14 -0800 (PST)]]>
 </data>

Gives:

 Sat Nov 19 18:50:15 2016 (1672822)                             
 Sat, 19 Nov 2016 18:50:14 -0800 (PST)       


来源:https://stackoverflow.com/questions/41365068/unable-to-check-cdata-in-xml-using-xmleventreader-in-stax

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