Unable to check CDATA in XML using XMLEventReader in Stax

前端 未结 2 1687
天命终不由人
天命终不由人 2021-01-16 18:02

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

The following is the sample:

 HEADERS
                       


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-16 18:19

    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

     
        
        
     
    

    Gives:

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

提交回复
热议问题