java dom4j content is not allowed in prolog

        前段时间用dom4j解析xml时碰到了个异常 content is not allowed in prolog,估计是编码问题,后来在网上找到了答案,具体看以下的代码就知道咋回事了

 

 

import java.io.*;
import java.nio.charset.Charset;
import javax.xml.parsers.*;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ContentNotAllowedInProlog {
  private static void parse(InputStream stream) throws SAXException,
      ParserConfigurationException, IOException {
    SAXParserFactory.newInstance().newSAXParser().parse(stream,
        new DefaultHandler());
  }

  public static void main(String[] args) {
    String[] encodings = { "UTF-8", "UTF-16", "ISO-8859-1" };
    for (String actual : encodings) {
      for (String declared : encodings) {
        if (actual != declared) {
          String xml = "<?xml version='1.0' encoding='" + declared
              + "'?><x/>";
          byte[] encoded = xml.getBytes(Charset.forName(actual));
          try {
            parse(new ByteArrayInputStream(encoded));
            System.out.println("HIDDEN ERROR! actual:" + actual + " " + xml);
          } catch (Exception e) {
            System.out.println(e.getMessage() + " actual:" + actual + " xml:"
                + xml);
          }
        }
      }
    }
  }
}
 

这段代码是老外分析的,原文http://illegalargumentexception.blogspot.com/2010/09/java-content-is-not-allowed-in-prolog.html

感觉帮助颇大。

 

 

 

你可能感兴趣的:(java,xml,dom4j)