XML解析使用SAX黑莓

问题描述:

我想分析下面的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

您可以使用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