2012-08-10 98 views
1

我想分析下面的XML文件:XML解析使用SAX黑莓

<login> 
    <address id="1"> 
     <username>mahesh</username> 
     <password>1234</password> 
    </address> 

    <address id="2"> 
     <username>admin</username> 
     <password>admin</password> 
    </address> 

    <address id="3"> 
     <username>a</username> 
     <password>a</password> 
    </address> 
</login> 

任何一個能幫助我嗎?給我一些示例代碼來解析它使用SAX解析器。我想從httpConnection方法獲取這個文件。我是BB發展的新手。

+1

http://whathaveyoutried.com/ – Nikola 2012-08-10 12:40:04

+0

請參閱此鏈接http://rincethomas.blogspot.in/2012/04/xml-parsing-in-bb.html – Signare 2012-08-10 13:48:15

+0

這裏根登錄 – Signare 2012-08-10 13:50:00

回答

2

您可以使用Dom & Sax解析器進行XML解析。

從HTTP請求&調用Xml的代碼段比使用Sax Parser解析它。

SAXParserImpl saxparser = new SAXParserImpl(); 
ListParser receivedListHandler=new ListParser(); 
static DataInputStream din = null; 
public static String response; 


    HttpConnection hc = null; 
     OutputStream os; 
      try 
      { 
       final String url ="<Enter URL for Xml Http Address>"+ InitClass.getConnectionString()+";ConnectionTimeout=25000"; 


       hc = (HttpConnection)Connector.open(url); 

       os = hc.openOutputStream(); 
       os.write(postDataBytes); 

       if (hc.getResponseCode() == 200) 
        din = hc.openDataInputStream(); 
       else 
        response = "" + hc.getResponseCode(); 
       saxparser.parse(din, receivedListHandler); 
      } 
      catch (Exception e) 
      { 

      } 
      finally 
      { 
       try 
       { 
        if(din!=null) 
         din.close(); 
        din = null; 
        if(hc!=null) 
         hc.close(); 
        hc = null; 
       } 
       catch (Exception e) { } 
      } 

/*解析類*/

public class ListParser extends DefaultHandler 
{ 
private String Key=""; 
private Hashtable ht=new Hashtable(); 
vector vec = new Vector(); 
public ListParser() 
{ 

} 
/** 
* Gets called, whenever a Xml is start . 
*/ 
public void startDocument() throws SAXException 
{ 

} 
/** 
* Gets called, whenever a Xml is End . 
*/ 
public void endDocument() throws SAXException 
{ 


} 
/** 
* Gets called, whenever a new tag is found. 
*/ 
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException 
{ 
    if(name.equals("address")) 
    { 
     ht = null; 
     ht = new Hashtable(); 
    } 
    else if(name.equals("login")) 
    { 

    } 
    Key=name; 
} 

/** 
* Gets called, whenever a closed tag is found. 
*/ 
public void endElement(String uri, String localName, String name) throws SAXException 
{ 
    if(name.equals("address")) 
    { 
     vec.addElement(ht); 
    } 
} 
public void characters(char[] ch, int start, int length) throws SAXException 
{ 
    String element=new String(ch, start, length); 
    ht.put(Key, element); 
} 
} 

它將分析XML,並會爲您提供在向量VEC數據在哈希表中每XML標籤。

+0

嗨shashank,當我使用上面的代碼來解析我的XML文件我沒有得到向量上的最後一個節點值,我沒有得到相應的地址節點的ID值,你可以給我的詳細代碼 – mahesh141 2012-08-25 05:57:44

+0

您是否根據您的XML更改地址和登錄? 您需要更改以獲取其中的值。 – 2012-08-25 06:17:07