XML problem with Java

Status
Not open for further replies.

Nimdok

Ars Scholae Palatinae
1,214
I'm trying to write a character out to a file using the Java 1.4 XML transform API. The character is retrieved from a java.awt.event.KeyEvent, from function getKeyChar().

Basically, when a KEY_TYPED KeyEvent is generated from a Ctrl-o, it returns the following character:

According to the documentation, this is: "the Unicode character defined for this key event"

I write the file out to disk with no problems, but when I read this file back in I get the following error:

org.xml.sax.SAXParseException: Illegal XML character: .
at org.apache.crimson.parser.InputEntity.fatal(InputEntity.java:1100)
at org.apache.crimson.parser.InputEntity.getc(InputEntity.java:360)
at org.apache.crimson.parser.Parser2.getc(Parser2.java:3009)
at org.apache.crimson.parser.Parser2.parseLiteral(Parser2.java:712)
at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1399)
at org.apache.crimson.parser.Parser2.content(Parser2.java:1779)
at org.apache.crimson.parser.Parser2.maybeElement(Parser2.java:1507)
at org.apache.crimson.parser.Parser2.parseInternal(Parser2.java:500)
at org.apache.crimson.parser.Parser2.parse(Parser2.java:305)
at org.apache.crimson.parser.XMLReaderImpl.parse(XMLReaderImpl.java:442)
at org.apache.crimson.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:185)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:86)
at com.mtp.pounder.PounderReader.read(PounderReader.java:88)

I looked at the file and the character appears to be written out OK. Does anyone have any ideas?
 
you need to specify the encoding when writing out the stream to a file using OutputStreamWriter(OutputStream out, String enc)
Then you need to make sure you set the XML to have the same encoding.

something like (might not compile but you'll get the idea)

Code:
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root></root>";
FileOutputSteam fileOut = new FileOutputStream("fileName.xml");
OutputStreamWriter writer = new OutputStreamWriter(fileOut, "UTF-8");
writer.write(xml);
writer.close;

you can obviously wrapp in a buffered writer etc and will need to do the same but opposite InputStreamReader methods when reading the file. Java will use the default platform encoding when writing/reading characters from files which is causing the troubles since you XML has characters that aren't allowed.

On the other hand... check to make sure you are using the latest XML parsers etc. I spent a whole day trying to track down a similar problem before i realized the IBM jvm comes with a really old xerces.jar in the lib/ext dir.
 
Status
Not open for further replies.