【问题标题】:StaX: Content not allowed in prologStaX:序言中不允许的内容
【发布时间】:2014-07-23 12:57:12
【问题描述】:

我在下面有以下(测试)XML 文件和使用 StaX 的 Java 代码。我想将此代码应用于大约 30 GB 大但元素相当小的文件,所以我认为 StaX 是一个不错的选择。我收到以下错误:

线程“main”中的异常 javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1] Message: Content is not allowed in prolog 在 com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:598) 在 at.tuwien.mucke.util.xml.staxtest.StaXTest.main(StaXTest.java:18) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 在 java.lang.reflect.Method.invoke(Method.java:601) 在 com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

<?xml version='1.0' encoding='utf-8'?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <price>44.95</price>
      <description>An in-depth look at creating applications 
       with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <price>5.95</price>
      <description>A former architect battles corporate zombies, 
       an evil sorceress, and her own childhood to become queen 
       of the world.</description>
    </book>
</catalog>

代码如下:

package xml.staxtest;

import java.io.*;
import javax.xml.stream.*;

public class StaXTest {

public static void main(String[] args) throws Exception  {

    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = xif.createXMLStreamReader(new FileReader("D:/Data/testFile.xml"));

    while(streamReader.hasNext()){
        int eventType = streamReader.next();

        if(eventType == XMLStreamReader.START_ELEMENT){
            System.out.println(streamReader.getLocalName());
        }

        //... more to come here later ...
    }
}

}

【问题讨论】:

  • 您是否尝试过删除 xml 声明? (推荐但仍然是可选的)
  • 是的。而且我还发现当文件为空时我得到相同的结果。文件本身似乎有问题......编码?隐藏角色?
  • 解决了!我添加了 并且必须将其存储在 ANSI 中(因为 Notepad++ 假定为 UTF-8。愚蠢!
  • 我认为这不是一个好主意。 XML 默认使用 UTF-8 是有原因的。我很确定您的问题源于(不必要的)使用 UTF-8 BOM (Byte Order Mark)。删除它(并阻止任何插入它的应用程序这样做),你应该没问题。

标签: java xml stax


【解决方案1】:

解决了!

我在定义&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt; 中添加了编码,我必须将它存储在ANSI 中(因为Notepad++ 假定为UTF-8)。愚蠢的!

【讨论】:

    猜你喜欢
    • 2013-07-10
    • 2023-04-10
    • 2020-07-03
    • 2016-10-11
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多