org.xml.sax.SAXParseException: Content is not allowed in prolog

我有一个基于Java的web服务客户机连接到Java web服务(在Axis1框架上实现)。

我得到以下异常在我的日志文件:

Caused by: org.xml.sax.SAXParseException: Content is not allowed in prolog.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLScanner.reportFatalError(Unknown Source)
at org.apache.xerces.impl.XMLDocumentScannerImpl$PrologDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
at org.apache.ws.axis.security.WSDoAllReceiver.invoke(WSDoAllReceiver.java:114)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:198)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
702612 次浏览

这意味着XML格式不正确,或者响应体根本不是XML文档。

尝试在序言中的encoding="UTF-8"字符串和结束的?>字符串之间添加一个空格。在XML中,prolog在文档的开头指定这个括号-问号分隔的元素(而stackoverflow中的标记prolog指的是编程语言)。

补充道:文件序言部分前面的破折号是吗?这将是那里的错误,在序言-<?xml version="1.0" encoding="UTF-8"?>前面有数据。

把你的文档设置成这样:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
%children%
</root>

在我的例子中,删除'encoding="UTF-8"'属性完全有效。

这看起来像是一个字符集编码问题,可能是因为您的文件不是真正的UTF-8格式。

这通常是由XML声明前的空白引起的,但它可以是任何文本,就像破折号或任何字符一样。我说通常是由空白引起的,因为人们认为空白总是可以忽略的,但这里不是这样的。


另一件经常发生的事情是utf - 8 BOM(字节顺序标记),如果将文档作为字符流而不是字节流提交给XML解析器,则在XML声明之前允许将其视为空白。

如果模式文件(.xsd)被用来验证xml文件,并且其中一个模式文件有utf - 8 BOM,也会发生同样的情况。

实际上除了尤里·祖巴雷夫的帖子

当您传递一个不存在的xml文件给解析器时。比如你通过

new File("C:/temp/abc")

当文件系统中只存在C:/temp/abc.xml文件时

无论哪种情况

builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
document = builder.parse(new File("C:/temp/abc"));

DOMParser parser = new DOMParser();
parser.parse("file:C:/temp/abc");

都给出相同的错误消息。

非常令人失望的bug,因为下面的跟踪

javax.servlet.ServletException
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
...
Caused by: org.xml.sax.SAXParseException: Content is not allowed in prolog.
... 40 more

没有说任何关于“文件名不正确”或“这样的文件不存在”的事实。在我的情况下,我有绝对正确的xml文件,不得不花2天来确定真正的问题。

这只是对未来的一个额外的想法。出现这种错误的情况可能是,当一个XML窗口作为活动显示时,用户只是随机地按下删除键或其他键,而没有注意。我以前在我的web应用程序中使用struts.xml文件时就遇到过这种情况。笨拙的手肘……

我也得到了同样的结果

XML reader error: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,2] Message: Reference is not allowed in prolog.

,当我的应用程序为RestFull Webservice调用创建XML响应时。 在创建XML格式字符串时,我将<和>替换为<>然后错误就发生了,我得到了正确的响应。不知道它是如何工作的,但它确实工作了

样本:

String body = "<ns:addNumbersResponse xmlns:ns=\"http://java.duke.org\"><ns:return>"
+sum
+"</ns:return></ns:addNumbersResponse>";

我也有同样的问题。

首先,我将XML文件下载到本地桌面,在将文件导入到门户服务器时,我得到了Content is not allowed in prolog。甚至从视觉上看文件对我来说很好,但不知为何它被损坏了。

所以我重新下载了同样的文件,尝试了同样的,它工作了。

刚刚花了4个小时在WSDL中跟踪一个类似的问题。结果是WSDL使用了导入另一个名称空间XSD的XSD。这个导入的XSD包含以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<schema targetNamespace="http://www.xyz.com/Services/CommonTypes" elementFormDefault="qualified"
xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:CommonTypes="http://www.xyz.com/Services/CommonTypes">


<include schemaLocation=""></include>
<complexType name="RequestType">
<....

注意空的include元素!这是我痛苦的根源。我猜这是Egor的文件没有发现上面的问题的变化。

对令人失望的错误报告+1。

我的回答可能对你没有帮助,但对这个问题有一般的帮助。

当你看到这种异常时,你应该尝试在任何十六进制编辑器中打开你的xml文件,有时你会在文件开头看到文本编辑器没有显示的额外字节。

删除它们,您的xml将被解析。

我在尝试用freemarker解析XML文档时遇到了同样的问题(并且已经解决了)。

我在XML文件头之前没有空格。

问题发生在当且仅当文件编码和XML编码属性不同时。(例如:UTF-8文件与UTF-16属性的头)。

所以我有两种解决问题的方法:

  1. 更改文件本身的编码
  2. 将标头UTF-16改为UTF-8

我们最近也遇到了同样的问题,结果是一个错误的URL,结果是一个标准的403 HTTP响应(显然不是客户端正在寻找的有效XML)。我将分享细节,以防在同一上下文中遇到这个问题的人:

这是一个基于Spring的web应用程序,其中“JaxWsPortProxyFactoryBean”bean被配置为公开远程端口的代理。

<bean id="ourPortJaxProxyService"
class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean"
p:serviceInterface="com.amir.OurServiceSoapPortWs"
p:wsdlDocumentUrl="${END_POINT_BASE_URL}/OurService?wsdl"
p:namespaceUri="http://amir.com/jaxws" p:serviceName="OurService"
p:portName="OurSoapPort" />

END_POINT_BASE_URL是在承载web应用程序的Tomcat实例的“setenv.sh”中配置的环境变量。该文件的内容是这样的:

export END_POINT_BASE_URL="http://localhost:9001/BusinessAppServices"
#export END_POINT_BASE_URL="http://localhost:8765/BusinessAppServices"

每行后面缺少的“;”会导致URL格式错误,从而导致错误响应。也就是说,不是“BusinessAppServices/OurService?”URL在“/”之前有一个CR。“TCP/IP监视器”在排除问题时非常方便。

如果所有这些都失败了,以二进制格式打开文件,以确保文件开头没有滑稽字符[文件开头的3个不可打印字符,它们将文件标识为utf-8]。我们这样做了,并找到了一些。因此,我们将文件从utf-8转换为ASCII,它成功了。

对于同样的问题,我已经删除了以下一行,

  File file = new File("c:\\file.xml");
InputStream inputStream= new FileInputStream(file);
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");

它工作得很好。不知道为什么UTF-8会出问题。为了让我感到震惊,它对UTF-8也很有效。

我使用windows 7 32位和Netbeans IDE与Java *jdk1.6.0_13*。不知道它是怎么运作的。

正如Mike Sokolov已经指出的那样,其中一个可能的原因是在标记之前存在一些字符(如空白)。

如果您的输入XML被读取为字符串(而不是字节数组),那么您将读取 可以使用以下代码替换您的输入字符串,以确保所有“不必要的”

. XML标记前的字符被删除
inputXML=inputXML.substring(inputXML.indexOf("<?xml"));

但是,您需要确保输入xml以xml标记开始。

我按照指示找到在这里,我得到了同样的错误。

我尝试了几件事来解决它(即改变编码,键入XML文件而不是复制粘贴它等)在记事本和XML记事本,但没有工作。

当我编辑并保存我的XML文件在notepad++(编码-> utf-8没有BOM)时,问题得到了解决

在我的例子中,我得到了这个错误,因为我使用的API可以返回XML或JSON格式的数据。当我使用浏览器测试它时,它默认为XML格式,但是当我从Java应用程序调用相同的调用时,API返回JSON格式的响应,这自然会触发解析错误。

就连我也遇到过类似的问题。原因是文件开头的一些垃圾字符。

修复:只需在文本编辑器中打开文件(在Sublime文本上测试)删除任何缩进,如果文件中有任何,并复制粘贴文件的所有内容在一个新文件中并保存它。它!。当我运行新文件时,它运行时没有任何解析错误。

我把Dineshkumar的代码修改为正确验证我的XML文件:

.
import org.apache.log4j.Logger;


public class Myclass{


private static final Logger LOGGER = Logger.getLogger(Myclass.class);


/**
* Validate XML file against Schemas XSD in pathEsquema directory
* @param pathEsquema directory that contains XSD Schemas to validate
* @param pathFileXML XML file to validate
* @throws BusinessException if it throws any Exception
*/
public static void validarXML(String pathEsquema, String pathFileXML)
throws BusinessException{
String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
String nameFileXSD = "file.xsd";
String MY_SCHEMA1 = pathEsquema+nameFileXSD);
ParserErrorHandler parserErrorHandler;
try{
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA);
		

Source [] source = {
new StreamSource(new File(MY_SCHEMA1))
};
Schema schemaGrammar = schemaFactory.newSchema(source);


Validator schemaValidator = schemaGrammar.newValidator();
schemaValidator.setErrorHandler(
parserErrorHandler= new ParserErrorHandler());
		

/** validate xml instance against the grammar. */
File file = new File(pathFileXML);
InputStream isS= new FileInputStream(file);
Reader reader = new InputStreamReader(isS,"UTF-8");
schemaValidator.validate(new StreamSource(reader));
		

if(parserErrorHandler.getErrorHandler().isEmpty()&&
parserErrorHandler.getFatalErrorHandler().isEmpty()){
if(!parserErrorHandler.getWarningHandler().isEmpty()){
LOGGER.info(
String.format("WARNING validate XML:[%s] Descripcion:[%s]",
pathFileXML,parserErrorHandler.getWarningHandler()));
}else{
LOGGER.info(
String.format("OK validate  XML:[%s]",
pathFileXML));
}
}else{
throw new BusinessException(
String.format("Error validate  XML:[%s], FatalError:[%s], Error:[%s]",
pathFileXML,
parserErrorHandler.getFatalErrorHandler(),
parserErrorHandler.getErrorHandler()));
}
}
catch(SAXParseException e){
throw new BusinessException(String.format("Error validate XML:[%s], SAXParseException:[%s]",
pathFileXML,e.getMessage()),e);
}
catch (SAXException e){
throw new BusinessException(String.format("Error validate XML:[%s], SAXException:[%s]",
pathFileXML,e.getMessage()),e);
}
catch (IOException e) {
throw new BusinessException(String.format("Error validate XML:[%s],
IOException:[%s]",pathFileXML,e.getMessage()),e);
}
	

}


}

对于所有得到这个错误的人: 警告:卡特琳娜。start using conf/server.xml: Content is not allowed in prolog.

.xml

信息量不大…但这实际上意味着conf/server.xml文件中有垃圾。

我在其他XML文件中看到过这个错误。此错误可能由使用引入垃圾的文本编辑器进行更改引起。

验证文件中是否有垃圾的方法是使用“HEX编辑器”打开它,如果你在这个字符串之前看到任何字符

     "<?xml version="1.0" encoding="UTF-8"?>"

就好像这是垃圾一样

     "‰ŠŒ<?xml version="1.0" encoding="UTF-8"?>"

那是你的问题.... 解决方案是使用一个好的十六进制编辑器..一个将允许您保存不同类型的编码文件..< / p >

然后保存为UTF-8。 一些使用XML文件的系统可能需要将其保存为UTF NO BOM 这意味着“没有字节顺序标记”

希望这能帮助到一些人!!

有时是代码的问题,而不是XML

下面的代码,

Document doc = dBuilder.parse(new InputSource(new StringReader("file.xml")));

也会导致这个错误,

[致命错误]:1:1:内容不允许在prolog.org.xml. saxx . saxparseexception;lineNumber: 1;columnNumber: 1;序言中不允许有内容。

因为它试图解析字符串字面量"file.xml"(而不是file.xml文件的内容)并失败,因为"file.xml"作为字符串不是格式良好的XML。

修正:删除StringReader():

Document doc = dBuilder.parse(new InputSource("file.xml"));

类似地,脏缓冲区问题会在实际XML之前留下残留的垃圾。如果您仔细检查了XML,仍然得到这个错误,请记录传递给解析器的确切内容;有时实际被解析的内容是令人惊讶的。

春天我也有同样的问题

MarshallingMessageConverter

通过预处理代码。

也许有人会需要理由: 读取字节。,我忘记了读取是一个方向操作。 你不能读两次。

我所尝试过的[没有成功]

在我的情况下,我的应用程序中的web.xml有额外的空间。甚至 i删除;它没有起作用!

我正在我的tomcat中使用logging.propertiesweb.xml,但即使在我恢复后,错误仍然存在!

解决方案

具体来说,我试着做加法

org.apache.catalina.filters.ExpiresFilter.level = FINE

Tomcat expire filter is not working correct . sh Tomcat expire filter is not working correct

extra space

尝试在apache.common .io中使用BOMInputStream:

public static <T> T getContent(Class<T> instance, SchemaType schemaType, InputStream stream) throws JAXBException, SAXException, IOException {


JAXBContext context = JAXBContext.newInstance(instance);
Unmarshaller unmarshaller = context.createUnmarshaller();
Reader reader = new InputStreamReader(new BOMInputStream(stream), "UTF-8");


JAXBElement<T> entry = unmarshaller.unmarshal(new StreamSource(reader), instance);


return entry.getValue();
}

首先清理项目,然后重建项目。我也面临着同样的问题。这之后一切都好起来了。

对我来说,构建——>清洁修复了一切!

我在mac中解析info.plist文件时遇到了同样的问题。但是,使用以下命令将该文件转换为XML解决了这个问题。

plutil -convert xml1 info.plist

希望这能帮助到别人。

修复Unix / Linux系统上的BOM问题:

  1. 检查是否有不需要的BOM字符: hexdump -C myfile.xml | more 一个不需要的BOM字符将以...<?xml>

  2. 的形式出现在文件的开头
  3. 或者,执行file myfile.xml。带有BOM字符的文件将显示为:myfile.xml: XML 1.0 document text, UTF-8 Unicode (with BOM) text

  4. 修复单个文件:tail -c +4 myfile.xml > temp.xml && mv temp.xml myfile.xml

  5. 重复1或2检查文件是否已被清除。也许做view myfile.xml检查内容是否保留也是明智的。

下面是一个bash脚本来清理整个XML文件文件夹:

#!/usr/bin/env bash


# This script is to sanitise XML files to remove any BOM characters


has_bom() { head -c3 "$1" | LC_ALL=C grep -qe '\xef\xbb\xbf'; }


for filename in *.xml ; do
if has_bom ${filename}; then
tail -c +4 ${filename} > temp.xml
mv temp.xml ${filename}
fi
done


我在一些XML文件中遇到了同样的问题,我解决了用ANSI编码(Windows-1252)读取文件和用Python中的一个小脚本编写UTF-8编码的文件。我尝试使用notepad++,但我没有成功:

import os
import sys


path = os.path.dirname(__file__)


file_name = 'my_input_file.xml'


if __name__ == "__main__":
with open(os.path.join(path, './' + file_name), 'r', encoding='cp1252') as f1:
lines = f1.read()
f2 = open(os.path.join(path, './' + 'my_output_file.xml'), 'w', encoding='utf-8')
f2.write(lines)
f2.close()

我遇到类似的问题与詹金斯junit报告插件。事实证明,您必须指定*.xml,即使您在主目录中创建junit xml。(测试报告xml: . xml . .(或targeted_directory /.xml)。

原因是标签之间的空格。

' <?xml version="1.0" encoding="UTF-8" standalone="no"?> <sign: ....'

删除空间。