2010-01-14 74 views
7

鑑於這種XML片段SAX解析 - 有效的方式來獲取文本節點

<?xml version="1.0"?> 
<catalog> 
    <book id="bk101"> 
     <author>Gambardella, Matthew</author> 

在SAX,很容易得到屬性值:

@Override 
public void startElement (String uri, String localName, 
       String qName, Attributes attributes) throws SAXException{ 
    if(qName.equals("book")){ 
     String bookId = attributes.getValue("id"); 
     ... 
    } 
} 

但要獲得一個文本節點的值,例如在<author>變量的值,它是相當困難...

private StringBuffer curCharValue = new StringBuffer(1024); 

@Override 
public void startElement (String uri, String localName, 
       String qName, Attributes attributes) throws SAXException { 
    if(qName.equals("author")){ 
     curCharValue.clear(); 
    } 
} 

@Override 
public void characters (char ch[], int start, int length) throws SAXException 
{ 
    //already synchronized 
    curCharValue.append(char, start, length); 
} 

@Override 
public void endElement (String uri, String localName, String qName) 
throws SAXException 
{ 
    if(qName.equals("author")){ 
     String author = curCharValue.toString(); 
    } 
} 
  1. 我不知道上面的示例甚至工作,你覺得這種做法是什麼?
  2. 有沒有更好的方法? (以獲得文本節點的值)
+1

這是最有效的我認爲... – nanda

回答

8

這是SAX的常用方法。

只是提防characters()可以不同於每個標籤一次。有關更多信息,請參閱此question。這是一個完整的example

否則,你可以給一個嘗試StAX

+0

很好的例子 - 謝謝! – jsh

1
public void startElement(String strNamespaceURI, String strLocalName, 
     String strQName, Attributes al) throws SAXException { 
     if(strLocalName.equalsIgnoreCase("HIT")) 
     { 
      String output1 = al.getValue("NAME"); 
      //this will work but how can we parse if NAME="abc" only  ? 
     } 

    }