How to encode characters from Oracle to XML?

前端 未结 3 1609
甜味超标
甜味超标 2021-01-12 05:28

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


        
相关标签:
3条回答
  • 2021-01-12 05:29

    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>
    
    0 讨论(0)
  • 2021-01-12 05:45

    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?

    0 讨论(0)
  • 2021-01-12 05:55

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

    0 讨论(0)
提交回复
热议问题