xml - 使用 StaX 忽略评论
问题描述
使用以下代码,我成功读取了 XML 文件。但是,当注释出现在节点中间时,阅读器将丢弃节点的其余部分。例如:
<text>thisismy<!--comment-->document</text>
将导致返回字符串“thisismy”,仅此而已。
我之前遇到过类似的问题,当我遇到特殊字符时,我将&其设置XMLInputFactory
为isCoalescing=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;
解决方案
推荐阅读
- python - 无法使用 pyinstaller 创建 .exe 文件
- java - 用户如何创建唯一的用户名
- javascript - 如何在 ES5 中导入 JSON 文件?
- flutter - 颤振无法访问静态变量
- javascript - 如何映射数组数组并返回它
- nestjs - 修复“Nest 无法解析 MovieService 的依赖项”。
- postgresql - 在遍历方法中维护初始 source_node -> end_node - Postgres
- javascript - 重定向如何在 javascript 中不起作用
- tinymce - 如何在 TinyMCE 5 file_picker_callback / callback() 函数中更新锚链接的 CSS 类和 rel 属性
- android - 从回收站视图列表中选择多个项目删除无法正常工作