Org xml sax saxparseexception ошибка

This is often caused by a white space before the XML declaration, but it could be any text, like a dash or any character. I say often caused by white space because people assume white space is always ignorable, but that’s not the case here.


Another thing that often happens is a UTF-8 BOM (byte order mark), which is allowed before the XML declaration can be treated as whitespace if the document is handed as a stream of characters to an XML parser rather than as a stream of bytes.

The same can happen if schema files (.xsd) are used to validate the xml file and one of the schema files has an UTF-8 BOM.

ParkerHalo's user avatar

ParkerHalo

4,3419 gold badges30 silver badges51 bronze badges

answered Oct 8, 2011 at 13:58

Mike Sokolov's user avatar

Mike SokolovMike Sokolov

6,9142 gold badges23 silver badges31 bronze badges

3

Actually in addition to Yuriy Zubarev’s Post

When you pass a nonexistent xml file to parser. For example you pass

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

when only C:/temp/abc.xml file exists on your file system

In either case

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

or

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

All give the same error message.

Very disappointing bug, because the following trace

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

doesn’t say anything about the fact of ‘file name is incorrect’ or ‘such a file does not exist’. In my case I had absolutely correct xml file and had to spent 2 days to determine the real problem.

rogerdpack's user avatar

rogerdpack

63k36 gold badges269 silver badges389 bronze badges

answered Nov 12, 2011 at 14:39

Egor's user avatar

EgorEgor

5515 silver badges8 bronze badges

7

Try adding a space between the encoding="UTF-8" string in the prolog and the terminating ?>. In XML the prolog designates this bracket-question mark delimited element at the start of the document (while the tag prolog in stackoverflow refers to the programming language).

Added: Is that dash in front of your prolog part of the document? That would be the error there, having data in front of the prolog, -<?xml version="1.0" encoding="UTF-8"?>.

answered Feb 28, 2011 at 12:46

hardmath's user avatar

hardmathhardmath

8,7532 gold badges37 silver badges65 bronze badges

1

I had the same problem (and solved it) while trying to parse an XML document with freemarker.

I had no spaces before the header of XML file.

The problem occurs when and only when the file encoding and the XML encoding attribute are different. (ex: UTF-8 file with UTF-16 attribute in header).

So I had two ways of solving the problem:

  1. changing the encoding of the file itself
  2. changing the header UTF-16 to UTF-8

JoshDM's user avatar

JoshDM

4,9387 gold badges43 silver badges72 bronze badges

answered Jul 22, 2013 at 14:03

2

It means XML is malformed or the response body is not XML document at all.

answered Feb 28, 2011 at 6:06

Yuriy Zubarev's user avatar

3

Just spent 4 hours tracking down a similar problem in a WSDL. Turns out the WSDL used an XSD which imports another namespace XSD. This imported XSD contained the following:

<?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">
        <....

Note the empty include element! This was the root of my woes. I guess this is a variation on Egor’s file not found problem above.

+1 to disappointing error reporting.

answered Nov 8, 2012 at 14:08

colin_froggatt's user avatar

My answer wouldn’t help you probably, but it help with this problem generally.

When you see this kind of exception you should try to open your xml file in any Hex Editor and sometime you can see additional bytes at the beginning of the file which text-editor doesn’t show.

Delete them and your xml will be parsed.

answered Mar 25, 2013 at 8:52

Igor Kustov's user avatar

Igor KustovIgor Kustov

7671 gold badge8 silver badges21 bronze badges

In my case, removing the ‘encoding=»UTF-8″‘ attribute altogether worked.

It looks like a character set encoding issue, maybe because your file isn’t really in UTF-8.

answered Oct 8, 2011 at 12:16

Jerome Louvel's user avatar

For the same issues, I have removed the following line,

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

It is working fine. Not so sure why that UTF-8 gives problem. To keep me in shock, it works fine for UTF-8 also.

Am using Windows-7 32 bit and Netbeans IDE with Java *jdk1.6.0_13*. No idea how it works.

answered Jan 27, 2014 at 10:05

Dineshkumar's user avatar

DineshkumarDineshkumar

1,4684 gold badges22 silver badges49 bronze badges

Sometimes it’s the code, not the XML

The following code,

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

will also result in this error,

[Fatal Error] :1:1: Content is not allowed in prolog.org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

because it’s attempting to parse the string literal, "file.xml" (not the contents of the file.xml file) and failing because "file.xml" as a string is not well-formed XML.

Fix: Remove StringReader():

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

Similarly, dirty buffer problems can leave residual junk ahead of the actual XML. If you’ve carefully checked your XML and are still getting this error, log the exact contents being passed to the parser; sometimes what’s actually being (tried to be) parsed is surprising.

answered Nov 17, 2017 at 20:11

kjhughes's user avatar

kjhugheskjhughes

106k27 gold badges181 silver badges240 bronze badges

1

First clean project, then rebuild project. I was also facing the same issue. Everything came alright after this.

answered Aug 26, 2018 at 13:39

Bibin Johny's user avatar

Bibin JohnyBibin Johny

3,1571 gold badge13 silver badges16 bronze badges

0

To fix the BOM issue on Unix / Linux systems:

  1. Check if there’s an unwanted BOM character:
    hexdump -C myfile.xml | more
    An unwanted BOM character will appear at the start of the file as ...<?xml>

  2. Alternatively, do file myfile.xml. A file with a BOM character will appear as: myfile.xml: XML 1.0 document text, UTF-8 Unicode (with BOM) text

  3. Fix a single file with: tail -c +4 myfile.xml > temp.xml && mv temp.xml myfile.xml

  4. Repeat 1 or 2 to check the file has been sanitised. Probably also sensible to do view myfile.xml to check contents have stayed.

Here’s a bash script to sanitise a whole folder of XML files:

#!/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

answered May 14, 2019 at 11:14

Lydia Ralph's user avatar

Lydia RalphLydia Ralph

1,4551 gold badge17 silver badges33 bronze badges

If all else fails, open the file in binary to make sure there are no funny characters [3 non printable characters at the beginning of the file that identify the file as utf-8] at the beginning of the file. We did this and found some. so we converted the file from utf-8 to ascii and it worked.

answered Jan 11, 2014 at 0:04

Ralph's user avatar

RalphRalph

311 bronze badge

As Mike Sokolov has already pointed it out, one of the possible reasons is presence of some character/s (such as a whitespace) before the tag.

If your input XML is being read as a String (as opposed to byte array) then you
can use replace your input string with the below code to make sure that all ‘un-necessary’
characters before the xml tag are wiped off.

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

You need to be sure that the input xml starts with the xml tag though.

answered Apr 11, 2014 at 19:29

Sahil J's user avatar

Sahil JSahil J

6856 silver badges10 bronze badges

What i have tried [Did not work]

In my case the web.xml in my application had extra space. Even after i deleted ; it did not work!.

I was playing with logging.properties and web.xml in my tomcat, but even after i reverted the error persists!.

Solution

To be specific i tried do adding

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

Tomcat expire filter is not working correctly

extra space

answered Feb 5, 2018 at 15:50

shareef's user avatar

shareefshareef

9,28513 gold badges59 silver badges89 bronze badges

0

I followed the instructions found here and i got the same error.

I tried several things to solve it (ie changing the encoding, typing the XML file rather than copy-pasting it ect) in Notepad and XML Notepad but nothing worked.

The problem got solved when I edited and saved my XML file in Notepad++ (encoding —> utf-8 without BOM)

answered Jul 29, 2014 at 22:21

BitCollector's user avatar

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.

answered Nov 18, 2014 at 15:09

zovits's user avatar

zovitszovits

90616 silver badges27 bronze badges

Just an additional thought on this one for the future. Getting this bug could be the case that one simply hits the delete key or some other key randomly when they have an XML window as the active display and are not paying attention. This has happened to me before with the struts.xml file in my web application. Clumsy elbows …

answered Feb 23, 2012 at 20:27

demongolem's user avatar

demongolemdemongolem

9,47436 gold badges90 silver badges105 bronze badges

1

I was also getting the same

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

, when my application was creating a XML response for a RestFull Webservice call.
While creating the XML format String I replaced the &lt and &gt with < and > then the error went off, and I was getting proper response. Not sure how it worked but it worked.

sample:

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

shareef's user avatar

shareef

9,28513 gold badges59 silver badges89 bronze badges

answered May 28, 2012 at 10:26

Satish M's user avatar

I had the same issue.

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.

Marko's user avatar

Marko

20.4k13 gold badges49 silver badges64 bronze badges

answered Aug 29, 2012 at 7:45

paresh's user avatar

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.

answered Sep 12, 2013 at 5:21

Amir Keibi's user avatar

Amir KeibiAmir Keibi

1,99128 silver badges45 bronze badges

For all those that get this error:
WARNING: Catalina.start using conf/server.xml: Content is not allowed in prolog.

Not very informative.. but what this actually means is that there is garbage in your conf/server.xml file.

I have seen this exact error in other XML files.. this error can be caused by making changes with a text editor which introduces the garbage.

The way you can verify whether or not you have garbage in the file is to open it with a «HEX Editor» If you see any character before this string

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

like this would be garbage

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

that is your problem….
The Solution is to use a good HEX Editor.. One that will allow you to save files with differing types of encoding..

Then just save it as UTF-8.
Some systems that use XML files may need it saved as UTF NO BOM
Which means with «NO Byte Order Mark»

Hope this helps someone out there!!

answered May 18, 2016 at 22:51

CA Martin's user avatar

CA MartinCA Martin

3072 silver badges7 bronze badges

1

For me, a Build->Clean fixed everything!

answered Dec 7, 2018 at 12:06

FabioStein's user avatar

FabioSteinFabioStein

7808 silver badges23 bronze badges

I had the same problem with some XML files, I solved reading the file with ANSI encoding (Windows-1252) and writing a file with UTF-8 encoding with a small script in Python. I tried use Notepad++ but I didn’t have success:

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

answered Oct 8, 2019 at 15:24

Ângelo Polotto's user avatar

Ângelo PolottoÂngelo Polotto

8,5232 gold badges38 silver badges37 bronze badges

1

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.

answered Feb 22, 2016 at 17:51

Aditya Gaykar's user avatar

Aditya GaykarAditya Gaykar

4701 gold badge5 silver badges10 bronze badges

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

}

answered Mar 27, 2016 at 6:28

RodH's user avatar

RodHRodH

134 bronze badges

Set your document to form like this:

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

Laurel's user avatar

Laurel

5,98514 gold badges31 silver badges58 bronze badges

answered Sep 27, 2011 at 3:34

Pavel's user avatar

PavelPavel

4,9207 gold badges50 silver badges69 bronze badges

0

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.

Learning Always's user avatar

answered Dec 27, 2017 at 11:19

Artem Ptushkin's user avatar

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

answered May 25, 2018 at 8:16

Giuseppe Milazzo's user avatar

I was having the same problem while parsing the info.plist file in my mac. However, the problem was fixed using the following command which turned the file into an XML.

plutil -convert xml1 info.plist

Hope that helps someone.

answered Apr 3, 2019 at 23:19

Reaz Murshed's user avatar

Reaz MurshedReaz Murshed

23.7k13 gold badges78 silver badges98 bronze badges

Мы используем синтаксический анализатор SAX для анализа XML-файла и получаем следующее сообщение об ошибке:

org.xml.sax.SAXParseException; systemId: ../src/main/resources/staff.xml;

  lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

Короче говоря, недопустимый текст или спецификация перед объявлением XML или другой кодировкой вызовут ошибку SAX – Содержимое не разрешено в прологе .

  • 1. Недопустимый текст перед объявлением XML.
  • 2. Спецификация в начале XML-файла.
  • 3. Другой формат кодирования
  • 4. Скачать Исходный Код
  • 5. Рекомендации

1. Недопустимый текст перед объявлением XML.

В начале XML-объявления любой текст вызовет Содержимое не разрешено в прологе ошибка.

Например, приведенный ниже XML-файл содержит дополнительную маленькую точку . перед объявлением XML.

.

    
        yong
        mook kim
        mkyong
        100000
    

Чтобы исправить это Удалите любой текст перед объявлением XML.


    
        yong
        mook kim
        mkyong
        100000
    

2. Спецификация в начале XML-файла.

Многие текстовые редакторы автоматически добавляют спецификацию в файл UTF-8.

Примечание Прочитайте следующие статьи:

  • Java добавляет и удаляет спецификацию из файла UTF-8
  • Википедия – Метка порядка байтов (спецификация)

Протестированный с Java 11 и Java 8, встроенный синтаксический анализатор SAX может правильно анализировать файл спецификации UTF-8; однако некоторые разработчики утверждали, что спецификация вызвала ошибку при анализе XML.

Чтобы исправить это , удалите спецификацию из файла UTF-8.

  1. Удалите спецификацию с помощью кода
  2. В notepad++ проверьте кодировку UTF-8 без спецификации .
  3. В Intellij IDEA прямо в файле выберите Удалить спецификацию .

P.S Многие редакторы текста или кода имеют функции для добавления или удаления метка порядка байтов (спецификация) для файла попробуйте найти нужную функцию в меню.

3. Другой формат кодирования

Различная кодировка также вызвала популярный XML Содержимое не допускается в прологе.

Например, XML-файл UTF-8.


    
        mkyong
        support
        5000
        
        
    
    
        yflow
        admin
        8000
        
    

И мы используем кодировку UTF-16 для анализа вышеупомянутого XML-файла в кодировке UTF-8.

  SAXParserFactory factory = SAXParserFactory.newInstance();

  try (InputStream is = getXMLFileAsStream()) {

      SAXParser saxParser = factory.newSAXParser();

      // parse XML and map to object, it works, but not recommend, try JAXB
      MapStaffObjectHandlerSax handler = new MapStaffObjectHandlerSax();

      // more options for configuration
      XMLReader xmlReader = saxParser.getXMLReader();
      xmlReader.setContentHandler(handler);

      InputSource source = new InputSource(is);

      // UTF-16 to parse an UTF-8 XML file
      source.setEncoding(StandardCharsets.UTF_16.toString());
      xmlReader.parse(source);

      // print all
      List result = handler.getResult();
      result.forEach(System.out::println);

  } catch (ParserConfigurationException | SAXException | IOException e) {
      e.printStackTrace();
  }

Выход

[Fatal Error] :1:1: Content is not allowed in prolog.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
at java.xml/com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1243)
at java.xml/com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:635)
at com.mkyong.xml.sax.ReadXmlSaxParser2.main(ReadXmlSaxParser2.java:45)

4. Скачать Исходный Код

$клон git $клон git

$компакт-диск java-xml

$cd src/основной/java/com/mkyong/xml/саксофон/

5. Рекомендации

  • Синтаксический анализатор Java SAX
  • Java добавляет и удаляет спецификацию из файла UTF-8
  • Википедия – Метка порядка байтов (спецификация)
  • В чем разница между UTF-8 и UTF-8 без спецификации?

Оригинал: “https://mkyong.com/java/sax-error-content-is-not-allowed-in-prolog/”



  • Метки



    bom, content, error, text, xml
Все реализованные интерфейсы:
Serializable
public class SAXParseException extends SAXException

Инкапсуляция ошибки разбора XML или предупреждения.

Это исключение может включать информацию для поиска ошибки в исходном XML-документе, как если бы она была Locator объекта Locator . Обратите внимание, что хотя приложение получит исключение SAXParseException в качестве аргумента для обработчиков в интерфейсе ErrorHandler , приложение фактически не обязано генерировать исключение; вместо этого он может просто прочитать содержащуюся в нем информацию и предпринять другое действие.

Поскольку это исключение является подклассом SAXException , оно наследует возможность обернуть другое исключение.

Since:
1.4, SAX 1.0
See Also:
  • SAXException
  • Locator
  • ErrorHandler
  • Serialized Form

Constructor Summary

Constructor Description
SAXParseException(String message,
String publicId,
String systemId,
int lineNumber,
int columnNumber)

Создайте новое исключение SAXParseException.

SAXParseException(String message,
String publicId,
String systemId,
int lineNumber,
int columnNumber,
Exception e)

Создайте новое исключение SAXParseException со встроенным исключением.

SAXParseException(String message,
Locator locator)

Создайте новое исключение SAXParseException из сообщения и локатора.

SAXParseException(String message,
Locator locator,
Exception e)

Оберните существующее исключение в SAXParseException.

Method Summary

Модификатор и тип Method Description
int getColumnNumber()

Номер колонки в конце текста,где произошло исключение.

int getLineNumber()

Номер строки в конце текста,где произошло исключение.

String getPublicId()

Получение публичного идентификатора объекта,в котором произошло исключение.

String getSystemId()

Получение системного идентификатора объекта,в котором произошло исключение.

String toString()

Переопределите toString для предоставления более подробного сообщения об ошибке.

Методы, объявленные в классе java.lang. Метательный

addSuppressed, fillInStackTrace, getLocalizedMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace

Методы, объявленные в классе java.lang. Объект

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Details

SAXParseException

public SAXParseException(String message, Locator locator)

Создайте новое исключение SAXParseException из сообщения и локатора.

Этот конструктор особенно полезен, когда приложение создает собственное исключение из обратного вызова ContentHandler .

Parameters:
message — сообщение об ошибке или предупреждении.
locator — объект локатора для ошибки или предупреждения (может быть нулевым).
See Also:
  • Locator

SAXParseException

public SAXParseException(String message, Locator locator, Exception e)

Оберните существующее исключение в SAXParseException.

Этот конструктор особенно полезен, когда приложение создает собственное исключение из обратного вызова ContentHandler и ему необходимо обернуть существующее исключение, которое не является подклассом SAXException .

Parameters:
message — сообщение об ошибке или предупреждении, либо значение null, чтобы использовать сообщение из встроенного исключения.
locator — объект локатора для ошибки или предупреждения (может быть нулевым).
e — Любое исключение.
See Also:
  • Locator

SAXParseException

public SAXParseException(String message, String publicId, String systemId, int lineNumber, int columnNumber)

Создайте новое исключение SAXParseException.

Этот конструктор наиболее полезен для авторов парсеров.

Все параметры, кроме сообщения, как если бы они были предоставлены Locator . Например, если системный идентификатор является URL-адресом (включая относительное имя файла), вызывающий должен полностью разрешить его перед созданием исключения.

Parameters:
message — сообщение об ошибке или предупреждении.
publicId — общедоступный идентификатор объекта, который сгенерировал ошибку или предупреждение.
systemId — системный идентификатор объекта, вызвавшего ошибку или предупреждение.
lineNumber — номер строки конца текста, вызвавшего ошибку или предупреждение.
columnNumber — номер столбца в конце текста, вызвавшего ошибку или предупреждение.

SAXParseException

public SAXParseException(String message, String publicId, String systemId, int lineNumber, int columnNumber, Exception e)

Создайте новое исключение SAXParseException со встроенным исключением.

Этот конструктор наиболее полезен для разработчиков синтаксического анализатора, которым необходимо обернуть исключение, не являющееся подклассом SAXException .

Все параметры, кроме сообщения и исключения, как если бы они были предоставлены Locator . Например, если системный идентификатор является URL-адресом (включая относительное имя файла), вызывающий должен полностью разрешить его перед созданием исключения.

Parameters:
message — сообщение об ошибке или предупреждении, либо значение null, чтобы использовать сообщение из встроенного исключения.
publicId — общедоступный идентификатор объекта, который сгенерировал ошибку или предупреждение.
systemId — системный идентификатор объекта, вызвавшего ошибку или предупреждение.
lineNumber — номер строки конца текста, вызвавшего ошибку или предупреждение.
columnNumber — номер столбца в конце текста, вызвавшего ошибку или предупреждение.
e — Еще одно исключение для встраивания в это.

Method Details

getPublicId

public String getPublicId()

Получение публичного идентификатора объекта,в котором произошло исключение.

Returns:
Строка,содержащая публичный идентификатор,или null,если таковой отсутствует.
See Also:
  • Locator.getPublicId()

getSystemId

public String getSystemId()

Получение системного идентификатора объекта,в котором произошло исключение.

Если системный идентификатор является URL,он будет полностью разрешен.

Returns:
Строка,содержащая идентификатор системы,или null,если он отсутствует.
See Also:
  • Locator.getSystemId()

getLineNumber

public int getLineNumber()

Номер строки в конце текста,где произошло исключение.

Первая строка-это строка 1.

Returns:
Целое число,представляющее номер строки,или -1,если строки нет.
See Also:
  • Locator.getLineNumber()

getColumnNumber

public int getColumnNumber()

Номер колонки в конце текста,где произошло исключение.

Первый столбец в строке-это позиция 1.

Returns:
Целое число,представляющее номер столбца,или -1,если столбца нет.
See Also:
  • Locator.getColumnNumber()

toString

public String toString()

Переопределите toString для предоставления более подробного сообщения об ошибке.

Overrides:
toString в классе SAXException
Returns:
Строковое представление этого исключения.


OpenJDK

19

  • Class SAXNotRecognizedException

  • Class SAXNotSupportedException

  • Interface XMLFilter

  • Interface XMLReader

[78] Санкт-Петербург

[47] Ленинградская область

[77] г. Москва

[01] Республика Адыгея (Адыгея)

[03] Республика Бурятия

[04] Республика Алтай

[05] Республика Дагестан

[07] Кабардино-Балкарская Республика

[09] Карачаево-Черкесская Республика

[10] Республика Карелия

[11] Республика Коми

[12] Республика Марий Эл

[13] Республика Мордовия

[14] Республика Саха (Якутия)

[15] Республика Северная Осетия — Алания

[16] Республика Татарстан

[17] Республика Тыва

[18] Удмуртская Республика

[19] Республика Хакасия

[20] Чеченская Республика

[21] Чувашская Республика — Чувашия

[22] Алтайский край

[23] Краснодарский край

[24] Красноярский край

[25] Приморский край

[26] Ставропольский край

[27] Хабаровский край

[28] Амурская область

[29] Архангельская область

[30] Астраханская область

[31] Белгородская область

[32] Брянская область

[33] Владимирская область

[34] Волгоградская область

[35] Вологодская область

[36] Воронежская область

[37] Ивановская область

[38] Иркутская область

[39] Калининградская область

[40] Калужская область

[42] Кемеровская область

[43] Кировская область

[44] Костромская область

[45] Курганская область

[46] Курская область

[48] Липецкая область

[50] Московская область

[51] Мурманская область

[52] Нижегородская область

[53] Новгородская область

[55] Омская область

[56] Оренбургская область

[57] Орловская область

[58] Пензенская область

[59] Пермский край

[60] Псковская область

[61] Ростовская область

[62] Рязанская область

[63] Самарская область

[64] Саратовская область

[65] Сахалинская область

[66] Свердловская область

[67] Смоленская область

[68] Тамбовская область

[69] Тверская область

[70] Томская область

[71] Тульская область

[72] Тюменская область

[73] Ульяновская область

[74] Челябинская область

[75] Забайкальский край

[76] Ярославская область

[79] Еврейская автономная область

[83] Ненецкий автономный округ

[86] Ханты-Мансийский автономный округ — Югра

[89] Ямало-Ненецкий автономный округ

[91] Республика Крым

[92] Севастополь

[93] Донецкая Народная Республика

[94] Луганская Народная Республика

[95] Херсонская область

Понравилась статья? Поделить с друзьями:
  • Oracle sql developer ошибка ввода вывода
  • Oracle home key ошибка
  • Oracle exception код ошибки
  • Oracle exception вывести ошибку
  • Oracle 01033 ошибка что значит