仅使用SAXParser解析CDATA

时间:2012-08-01 16:19:12

标签: java xml-parsing sax

快速提问:

如果我有这样的XML:

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

所以uid有两个孩子吗?其中一个Node.CDATA_SECTION_NODENode.TEXT_NODE之一。

实现这个快速类(扩展通常的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,"");
    }

}

输出的解析类似于:

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:    

从输出中我们可以看到方法characters()在节点uid内被调用两次,因此它识别这两个子节点。有没有办法知道哪一个是CDATA?哪一个是TEXT?

1 个答案:

答案 0 :(得分:3)

您应该查看LexicalHandler,它会告诉您有关CDATA开始/结束的信息。

请注意,SAX解析器可以根据需要多次(或少数)调用您的characters()方法,以便您构建一个字符串(您只知道在{被调用{1}},你不能依赖它来确定文档结构。