In my environment here I use Java to serialize the result set to XML.
It happens basically like this:
//foreach column of each row
xmlHandler.startElement(uri, lname, "column", attributes);
String chars = rs.getString(i);
xmlHandler.characters(chars.toCharArray(), 0, chars.length());
xmlHandler.endElement(uri, lname, "column");
The XML looks like this in Firefox:
<row num="69004">
<column num="1">10069</column>
<column num="2">sd</column>
<column num="3">FCVolume </column>
</row>
But when I parse the XML I get the a
org.xml.sax.SAXParseException: Character reference "" is an
invalid XML character.
My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML?
I found an interesting list in the Xml Spec:
According to that List its discouraged to use the Character #26 (Hex: #x1A).
The characters defined in the
following ranges are also discouraged.
They are either control characters or
permanently undefined Unicode
characters
See the complete ranges.
This code replaces all non-valid Xml Utf8 from a String:
public String stripNonValidXMLCharacters(String in) {
StringBuffer out = new StringBuffer(); // Used to hold the output.
char current; // Used to reference the current character.
if (in == null || ("".equals(in))) return ""; // vacancy test.
for (int i = 0; i < in.length(); i++) {
current = in.charAt(i);
if ((current == 0x9) ||
(current == 0xA) ||
(current == 0xD) ||
((current >= 0x20) && (current <= 0xD7FF)) ||
((current >= 0xE000) && (current <= 0xFFFD)) ||
((current >= 0x10000) && (current <= 0x10FFFF)))
out.append(current);
}
return out.toString();
}
its taken from Invalid XML Characters: when valid UTF8 does not mean valid XML
But with that I had the still UTF-8 compatility issue:
org.xml.sax.SAXParseException: Invalid byte 1 of 1-byte UTF-8 sequence
After reading XML - returning XML as UTF-8 from a servlet I just tried out what happens if I set the Contenttype like this:
response.setContentType("text/xml;charset=utf-8");
And it worked ....
Extensible Markup Language (XML) 1.0 says:
The ampersand character (&) and the
left angle bracket (<) must not appear
in their literal form, except when
used as markup delimiters, or within a
comment, a processing instruction, or
a CDATA section. If they are needed
elsewhere, they must be escaped using
either numeric character references or
the strings "&" and "<"
respectively. The right angle bracket
(>) may be represented using the
string ">", and must, for
compatibility, be escaped using either
">" or a character reference when
it appears in the string "]]>" in
content, when that string is not
marking the end of a CDATA section.
You can skip the encoding if you use CDATA:
<column num="1"><![CDATA[10069]]></column>
<column num="2"><![CDATA[sd&]]></column>
Which version of JRE are you running? Sax Project says:
J2SE 1.4 bundles an old version of
SAX2. How do I make SAX2 r2 or later available?