直接在characters方面里面打印不要判断,应该是有值得,主要是判断有问题 把有值得数据覆盖了。

解决方案 »

  1.   

    characters()这个方法 ,每个在标签开始时会触发一次,读到结尾时会触发一次, 比如 <TITLE>EmpireBurlesque</TITLE>  在读TITLE的时候会触发一次,</TITLE>的时候会再触发一次,第二次的值为""把第一次读的值给覆盖掉了, 所以在 characters()这个方法里面应该加个判断 boolean  isStartElement,判断是 startElement(isStartElement =true;) 状态还是 endElement (isStartElement =false;)package cn.touchmedia.sax;import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;public class MyContentHandler extends DefaultHandler {
    boolean isStartElement =false;
    String tagName;
    String title;
    String artist;
    String country;
    String company;
    String price;
    String year; @Override
    public void startDocument() throws SAXException {
    // TODO Auto-generated method stub
    System.out.println("startDocument");
    super.startDocument();
    } @Override
    public void endDocument() throws SAXException {
    // TODO Auto-generated method stub
    System.out.println("endDocument");
    super.endDocument();
    } @Override
    public void startElement(String uri, String localName, String qName,
    org.xml.sax.Attributes attributes) throws SAXException {
    // TODO Auto-generated method stub
    super.startElement(uri, localName, qName, attributes);
    tagName = qName;
    isStartElement =true;
    } @Override
    public void endElement(String uri, String localName, String qName)
    throws SAXException {
    // TODO Auto-generated method stub
    super.endElement(uri, localName, qName);
    if (qName=="CD") {
    this.printout();
    }
    isStartElement=false;
    } @Override
    public void characters(char[] ch, int start, int length)
    throws SAXException {
    // TODO Auto-generated method stub
    if(isStartElement){
    if (tagName == "TITLE"){
    title = new String(ch,start,length).trim();
    }else if (tagName=="ARTIST")
    artist = new String(ch, start, length).trim();
    else if (tagName=="COUNTRY")
    country = new String(ch, start, length).trim();
    else if (tagName=="COMPANY")
    company = new String(ch, start, length).trim();
    else if (tagName=="PRICE")
    price = new String(ch, start, length).trim();
    else if (tagName=="YEAR")
    year = new String(ch, start, length).trim();
    }
    }
    private void printout(){
    System.out.println(title+","+artist+","+company+","+country+","+price+","+year);
    }
    }
      

  2.   


    按照您说的修改了一下,的确OK了
    但我看MARS老师的视频,他都没有做判断,为何可以正常解析呢
      

  3.   

    http://www.iteye.com/topic/763895   去看下这个..