我无法检查XML中的CDATA并使用XMLEventReader读取它。
以下是样本:
<name>HEADERS</name>
<data>
<![CDATA[ Sat Nov 19 18:50:15 2016 (1672822)
]]>
<![CDATA[Sat, 19 Nov 2016 18:50:14 -0800 (PST)
]]>
</data>
我使用的Stax api的XMLEventReader如下:
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isCharacters()) {
System.out.println(event.asCharacters().isCData());
System.out.println(event.asCharacters().getData());
}
}
因此,当我读取字符的数据标记时,我得到event.asCharacters()。isCData()的错误。想知道如何在EventReader中检查CDATA并获得CDATA。
答案 0 :(得分:1)
使用以下模式:
switch (EventType) {
case XMLStreamConstants.CHARACTERS:
case XMLStreamConstants.CDATA:
System.out.println(r.getText());
break;
default:
break;
}
完整样本:
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);
}
}
}
}
使用/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>
给予:
Sat Nov 19 18:50:15 2016 (1672822)
Sat, 19 Nov 2016 18:50:14 -0800 (PST)
答案 1 :(得分:0)
设置属性,否则读者将忽略CDATA的事件类型。
JsonObject
请参见com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl,第3027行