Quick question:
if I have an XML like this one:
<?xml version="1.0" encoding="utf-8"?>
<cop xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="cop.xsd">
<auth>
<uid mioattributo="20">16<![CDATA[
function matchwo(a,b) ]]></uid>
</auth>
</cop>
so uid has two children right? One of Node.CDATA_SECTION_NODE and one of Node.TEXT_NODE.
Implementing this quick class (extending the usual DefaultHandler):
public class MyHandler extends DefaultHandler {
/**
* Logger for this class
*/
private static final Log log = LogFactory.getLog(MyHandler.class);
private StringBuilder sb;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
System.out.println("STARTUri: " + uri);
System.out.println("STARTLocalName: " + localName);
System.out.println("STARTqName: " + qName);
// for(int i=0;i<attributes.getLength();i++) {
// System.out.println("LocalName: "+attributes.getLocalName(i));
// System.out.println("Type: "+attributes.getType(i));
// System.out.println("qName: "+attributes.getQName(i));
// System.out.println("URI: "+attributes.getURI(i));
// System.out.println("Value: "+attributes.getValue(i));
// }
sb = new StringBuilder();
//super.startElement(uri, localName, qName, attributes);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
sb.append(ch, start, length);
System.out.println("TEMPORARY: " + sb.toString());
System.out.println();
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.println("ENDUri: " + uri);
System.out.println("ENDLocalName: " + localName);
System.out.println("ENDqName: " + qName);
System.out.println("Content: " + sb.toString());
sb.replace(0, sb.length()-1,"");
}
}
The parsing of the output would be something like:
Is Validating: true
STARTUri:
STARTLocalName: cop
STARTqName: cop
TEMPORARY:
STARTUri:
STARTLocalName: auth
STARTqName: auth
TEMPORARY:
STARTUri:
STARTLocalName: uid
STARTqName: uid
TEMPORARY: 16
TEMPORARY: 16
function matchwo(a,b)
ENDUri:
ENDLocalName: uid
ENDqName: uid
Content: 16
function matchwo(a,b)
TEMPORARY:
ENDUri:
ENDLocalName: auth
ENDqName: auth
Content:
TEMPORARY:
ENDUri:
ENDLocalName: cop
ENDqName: cop
Content:
From the output we can see that the method characters() is called twice inside the node uid so it recognizes the two children. Is there a way to know which one is the CDATA and which one is the TEXT?
You should look at the LexicalHandler which tells you about CDATA start/ends.
Note that the SAX parser is at liberty to call your
characters()method as many (or as few) times as it needs, in order for you to build up a string (which you only know is complete uponendElement()being called), and you can’t rely on it in order to determine document structure.