views:

2997

answers:

3

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&#26;</column>
    <column num="3">FCVolume                      </column>
</row>

But when I parse the XML I get the a

org.xml.sax.SAXParseException: Character reference "&#26" 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?

+1  A: 
eed3si9n
That would be a good solution, but I don't know how to output a CDATA section (I can only work with a sax xml handler and have no access to the stream itself). And if I put the CDATA in the chars, the <'s get encoded to >....
Andre Bossard
+4  A: 

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

Andre Bossard
A: 

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?

eed3si9n
J2SE 1.5. Anyway, thanks for the hint
Andre Bossard