日期:2014-05-18  浏览次数:20838 次

xml字符串解析成Document出错,求指导
我从别人的接口获取了一个xml的字符串,我需要对其进行处理,所以把这个字符串解析成Document。如下:
方法一:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document allDoc = (Document) factory.newDocumentBuilder().parse(new ByteArrayInputStream(allField.getBytes()));

方法二:
Document allDoc = new SAXReader().read(new ByteArrayInputStream(allField.getBytes()));

用的dom4j包,上面两种解析方式都出异常,如下:
异常一:[Fatal Error] :1:40: Content is not allowed in prolog.
org.xml.sax.SAXParseException: Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:249)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
at com.huawei.vbs.webservice.TMSSTest.getDoc(TMSSTest.java:29)
at com.huawei.vbs.webservice.TMSSTest.main(TMSSTest.java:41)
异常二:org.dom4j.DocumentException: Error on line 1 of document  : Content is not allowed in prolog. Nested exception: Content is not allowed in prolog.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.dom4j.io.SAXReader.read(SAXReader.java:343)
at com.huawei.vbs.webservice.TMSSTest.getDoc(TMSSTest.java:30)
at com.huawei.vbs.webservice.TMSSTest.main(TMSSTest.java:41)
Nested exception: 
org.xml.sax.SAXParseException: Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:174)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1414)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:1039)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)