2011-01-13 37 views
1

來讀取XML特殊字符當我嘗試使用SAX解析器讀取從Java的XML,它是無法讀取特殊字符無法用java

後元素存在的內容例如:

<title>It's too difficult</title> 

使用SAX解析器讀取數據後,它僅顯示

如何處理特殊字符。我的示例代碼如下

package com.test.java; 

import javax.xml.parsers.SAXParser; 
import javax.xml.parsers.SAXParserFactory; 

import org.xml.sax.Attributes; 
import org.xml.sax.SAXException; 
import org.xml.sax.helpers.DefaultHandler; 
public class ReadXMLUsingSAXParser { 




    public static void main(String argv[]) { 

    try { 

     SAXParserFactory factory = SAXParserFactory.newInstance(); 
     SAXParser saxParser = factory.newSAXParser(); 

     DefaultHandler handler = new DefaultHandler() { 

     int titleCount; 
     boolean title = false; 
     boolean description = false; 

     public void startElement(String uri, String localName, 
     String qName, Attributes attributes) 
     throws SAXException { 

     // System.out.println("Start Element :" + qName); 


     if (qName.equalsIgnoreCase("title")) { 
      title = true; 
      titleCount+=1; 
     } 

     if (qName.equalsIgnoreCase("description")) { 
      description = true; 
     } 

     } 

     public void endElement(String uri, String localName, 
      String qName) 
      throws SAXException { 

     // System.out.println("End Element :" + qName); 

     } 

     public void characters(char ch[], int start, int length) 
      throws SAXException { 


      if (title&&titleCount>2) { 
       System.out.println("title : " 
        + new String(ch, start, length)+":"+titleCount); 
       title = false; 
      } 

      if (description) { 
       System.out.println("description : " 
        + new String(ch, start, length)); 
       description = false; 
      } 

     } 

     }; 

     saxParser.parse("C:\\Documents and Settings\\sukumar\\Desktop\\sample.xml", handler); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    } 

} 
+1

http://stackoverflow.com/questions/4567636/java-sax-parser-split-calls-to-characters/4567654#4567654 – 2011-01-13 14:38:58

回答

4

characters(char ch[], int start, int length)梅索德不讀飽滿的線條,你應該存儲在一個StringBuffer的人物,並在endElemen方法使用它。

如:

private StringBuffer buffer = new StringBuffer(); 

public void endElement(String uri, String localName, 
     String qName) 
     throws SAXException { 

    if (qName.equalsIgnoreCase("title")) { 
     System.out.println("title: " + buffer); 
    }else if (qName.equalsIgnoreCase("description")) { 
     System.out.println("description: " + buffer); 
    } 
    buffer = new StringBuffer(); 
} 

public void characters(char ch[], int start, int length) 
     throws SAXException { 
    buffer.append(new String(ch, start, length)); 
} 
+0

感謝morja ......這真是棒極了..非常感謝。 – JavaGeek 2011-01-13 15:09:14