development

org.xml.sax.SAXParseException : 프롤로그에서 컨텐츠를 사용할 수 없습니다

big-blog 2020. 6. 13. 09:30
반응형

org.xml.sax.SAXParseException : 프롤로그에서 컨텐츠를 사용할 수 없습니다


Java 기반 웹 서비스 클라이언트가 Java 웹 서비스에 연결되어 있습니다 (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)

이것은 종종 XML 선언 전에 공백으로 인해 발생하지만 대시 나 문자와 같은 텍스트수 있습니다 . 사람들이 공백을 항상 무시할 수 있다고 가정하기 때문에 공백으로 인해 종종 발생한다고 말합니다.하지만 여기서는 그렇지 않습니다.


자주 발생하는 또 다른 한가지는 것입니다 UTF-8 BOM (바이트 순서 표시) 되는 XML 선언이 공백으로 처리하기 전에 문서를 XML 파서에 문자의 스트림로서가 아닌 바이트 스트림으로 넘겨 경우 허용 .

스키마 파일 (.xsd)을 사용하여 xml 파일의 유효성을 검사하고 스키마 파일 중 하나에 UTF-8 BOM 이있는 경우에도 마찬가지 입니다.


Yuriy Zubarev의 게시물 외에도 실제로

존재하지 않는 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");

모두 같은 오류 메시지가 나타납니다.

다음 추적 때문에 매우 실망스러운 버그

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 ​​일이 걸렸습니다.


encoding="UTF-8"프롤로그 문자열과 종료 사이에 공백을 추가하십시오 ?>. XML에서 프롤로그는 문서 시작시이 괄호로 묶인 물음표로 구분 된 요소를 지정합니다 (스택 오버플로의 태그 프롤로그는 프로그래밍 언어를 참조 함).

추가 : 문서의 프롤로그 부분 앞에 대시가 있습니까? 프롤로그 앞에 데이터가 있으면 오류가 발생 -<?xml version="1.0" encoding="UTF-8"?>합니다.


freemarker로 XML 문서를 구문 분석하는 동안 동일한 문제가 발생했습니다.

XML 파일 헤더 앞에 공백이 없었습니다.

파일 인코딩과 XML 인코딩 속성이 다른 경우에만 문제가 발생합니다 . (예 : 헤더에 UTF-16 속성이있는 UTF-8 파일).

그래서 두 가지 방법으로 문제를 해결했습니다.

  1. 파일 자체의 인코딩 변경
  2. 헤더 UTF-16을 UTF-8로 변경

XML이 잘못되었거나 응답 본문이 XML 문서가 아님을 의미합니다.


WSDL에서 비슷한 문제를 추적하기 위해 4 시간을 보냈습니다. 다른 네임 스페이스 XSD를 가져 오는 XSD를 사용하는 WSDL이 밝혀졌습니다. 가져온 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


필자의 경우 'encoding = "UTF-8"'특성을 모두 제거했습니다.

파일이 실제로 UTF-8이 아니기 때문에 문자 세트 인코딩 문제처럼 보입니다.


내 대답은 아마 도움이되지 않지만 일반적 으로이 문제에 도움이됩니다.

이런 종류의 예외가 표시되면 16 진 편집기에서 xml 파일을 열려고 시도하고 때로는 텍스트 편집기에 표시되지 않는 파일의 시작 부분에 추가 바이트를 볼 수 있습니다.

그것들을 삭제하면 XML이 파싱됩니다.


먼저 프로젝트를 정리 한 다음 프로젝트를 다시 빌드하십시오. 나는 또한 같은 문제에 직면했다. 그 후 모든 것이 잘되었습니다.


다른 모든 방법이 실패하면 파일을 바이너리로 열어 파일 시작 부분에 재미있는 문자 [파일 시작 부분에 파일을 utf-8로 식별하는 3 개의 인쇄 할 수없는 문자]가 없는지 확인하십시오. 우리는 이것을하고 일부를 발견했습니다. 그래서 우리는 파일을 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에서도 잘 작동합니다.

사용하고 윈도우 7 * jdk1.6.0_13 * 자바 32 비트 및 넷빈즈 IDE를. 어떻게 작동하는지 모르겠습니다.


Mike Sokolov가 이미 지적했듯이 가능한 이유 중 하나는 태그 앞에 일부 문자 (예 : 공백)가 있기 때문입니다.

입력 XML을 바이트 배열이 아닌 문자열로 읽는 경우 입력 문자열을 아래 코드로 바꾸어 xml 태그 전에 모든 '필요하지 않은'문자를 지울 수 있습니다.

inputXML=inputXML.substring(inputXML.indexOf("<?xml"));

입력 xml이 xml 태그로 시작하는지 확인해야합니다.


나는 여기에 있는 지침을 따르고 같은 오류가 발생했습니다.

메모장과 XML 메모장에서 인코딩을 변경하고 복사하여 붙여 넣는 대신 XML 파일을 입력하는 등 여러 가지 방법으로 시도했지만 아무것도 작동하지 않았습니다.

메모장에서 XML 파일을 편집하고 저장할 때 문제가 해결되었습니다. ++ (BOM이없는 인코딩-> utf-8)


이 오류가 발생하는 모든 경우 : 경고 : conf / server.xml을 사용하여 Catalina.start : 프롤로그에 내용이 허용되지 않습니다.

그다지 유익하지는 않습니다. 그러나 이것이 실제로 의미하는 것은 conf / server.xml 파일에 가비지가 있다는 것입니다.

다른 XML 파일에서이 정확한 오류를 보았습니다.이 오류는 가비지를 도입하는 텍스트 편집기로 변경하여 발생할 수 있습니다.

파일에 가비지가 있는지 여부를 확인할 수있는 방법은 "HEX 편집기"로 파일을 여는 것입니다.이 문자열 앞에 문자가 있으면

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

이 쓰레기처럼

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

문제는 .... 해결책은 훌륭한 HEX 편집기를 사용하는 것입니다. 다른 유형의 인코딩으로 파일을 저장할 수있는 방법입니다.

그런 다음 UTF-8로 저장하십시오. XML 파일을 사용하는 일부 시스템에서는 UTF NO BOM으로 저장해야 할 수 있습니다. "NO Byte Order Mark"

이것이 누군가를 도울 수 있기를 바랍니다!


때로는 XML이 아닌 코드입니다.

다음 코드

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

이 오류가 발생합니다.

[치명적 오류] : 1 : 1 : 내용이 prolog.org.xml.sax.SAXParseException에서 허용되지 않습니다. lineNumber : 1; columnNumber : 1; 프롤로그에는 콘텐츠가 허용되지 않습니다.

파일 "file.xml"의 내용이 아닌 문자열 리터럴을 구문 분석하려고 시도 하고 문자열이 XML 형식이 아니기 file.xml때문에 실패 "file.xml"합니다.

수정 : 제거 StringReader():

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

마찬가지로 더티 버퍼 문제는 실제 XML보다 잔여 정크를 남길 수 있습니다. XML을주의 깊게 검사 한 후에도이 오류가 계속 발생하면 파서에 전달되는 정확한 내용을 기록하십시오. 때때로 실제로 시도되고있는 것이 놀랍습니다.


내 경우에는 삭제 한 후에도 응용 프로그램 web.xml 에 여분의 공간이 생겨서 chage와 해당 수정 사항을 되돌려 야했고 예 , 내 바람둥이에서 logging.propertiesweb.xml가지고 놀고 있었지만 되 돌린 후에도 오류가 계속 표시되어 수정되었습니다)).

여분의 공간

구체적으로 org.apache.catalina.filters.ExpiresFilter.level = FINE 스택을 플로우에 대한 로깅을 추가하려고했습니다.


나를 위해, Build-> Clean은 모든 것을 고쳤습니다 !


Unix / Linux 시스템에서 BOM 문제를 해결하려면 다음을 수행하십시오.

  1. 원치 않는 BOM 문자가 있는지 확인 : hexdump -C myfile.xml | more파일의 시작 부분에 원치 않는 BOM 문자가 다음과 같이 나타납니다....<?xml>

  2. 또는을 수행하십시오 file myfile.xml. BOM 문자가 포함 된 파일은 다음과 같이 나타납니다.myfile.xml: XML 1.0 document text, UTF-8 Unicode (with BOM) text

  3. 다음을 사용하여 단일 파일을 수정하십시오. tail -c +4 myfile.xml > temp.xml && mv temp.xml myfile.xml

  4. 파일이 위생 처리되었는지 확인하려면 1 또는 2를 반복하십시오. 아마도 view myfile.xml내용을 확인하는 것이 합리적 이었습니다.

XML 파일의 전체 폴더를 삭제하는 bash 스크립트는 다음과 같습니다.

#!/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 창이 있고주의를 기울이지 않을 때 삭제 키 또는 다른 키를 무작위로 누르는 경우 일 수 있습니다. 내 웹 응용 프로그램에서 struts.xml 파일을 사용하여 이전에 이런 일이 발생했습니다. 서투른 팔꿈치 ...


나는 또한 같은 것을 받고 있었다

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

내 응용 프로그램이 RestFull 웹 서비스 호출에 대한 XML 응답을 만들 때. XML 형식 문자열을 만드는 동안 & lt 및 & gt를 <및>으로 바꾸면 오류가 발생하고 적절한 응답을 얻었습니다. 어떻게 작동했는지 확실하지 않지만 작동했습니다.

샘플 :

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

나는 같은 문제가 있었다.

First I downloaded the XML file to local desktop and I got Content is not allowed in prolog during the importing file to portal server. Even visually file was looking good to me but somehow it's was corrupted.

So I re-download the same file and tried the same and it worked.


We had the same problem recently and it turned out to be the case of a bad URL and consequently a standard 403 HTTP response (which obviously isn't the valid XML the client was looking for). I'm going to share the detail in case someone within the same context run into this problem:

This was a Spring based web application in which a "JaxWsPortProxyFactoryBean" bean was configured to expose a proxy for a remote port.

<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" />

The "END_POINT_BASE_URL" is an environment variable configured in "setenv.sh" of the Tomcat instance that hosts the web application. The content of the file is something like this:

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

The missing ";" after each line caused the malformed URL and thus the bad response. That is, instead of "BusinessAppServices/OurService?wsdl" the URL had a CR before "/". "TCP/IP Monitor" was quite handy while troubleshooting the problem.


In my case I got this error because the API I used could return the data either in XML or in JSON format. When I tested it using a browser, it defaulted to the XML format, but when I invoked the same call from a Java application, the API returned the JSON formatted response, that naturally triggered a parsing error.


Even I had faced a similar problem. Reason was some garbage character at the beginning of the file.

Fix : Just open the file in a text editor(tested on Sublime text) remove any indent if any in the file and copy paste all the content of the file in a new file and save it. Thats it!. When I ran the new file it ran without any parsing errors.


I took code of Dineshkumar and modified to Validate my XML file correctly:

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);
	}
	
}

}


Set your document to form like this:

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

I had the same issue with spring

MarshallingMessageConverter

and by pre-proccess code.

Mayby someone will need reason: BytesMessage #readBytes - reading bytes.. and i forgot that reading is one direction operation. You can not read twice.


Try with BOMInputStream in apache.commons.io:

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();
}

info.plist내 Mac 에서 파일 을 구문 분석하는 동안 동일한 문제가 발생했습니다 . 그러나 파일을 XML로 바꾸는 다음 명령을 사용하여 문제가 해결되었습니다.

plutil -convert xml1 info.plist

누군가에게 도움이 되길 바랍니다

참고 URL : https://stackoverflow.com/questions/5138696/org-xml-sax-saxparseexception-content-is-not-allowed-in-prolog

반응형