StaX:prolog中不允许使用内容

时间:2014-06-03 08:55:27

标签: java xml stax

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

线程中的异常" main" javax.xml.stream.XMLStreamException:[row,col]处的ParseError:[1,1]消息:prolog中不允许使用内容     at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:598)     at at.tuwien.mucke.util.xml.staxtest.StaXTest.main(StaXTest.java:18)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)     at 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 ...
    }
}

}

1 个答案:

答案 0 :(得分:1)

解决了!

我在定义<?xml version="1.0" encoding="ISO-8859-1" ?>中添加了编码,我必须将其存储在ANSI中(如Notepad ++假设为UTF-8)。愚蠢!