1

我想解析以下 xml 文件:

<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开发的新手。

4

1 回答 1

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,并在每个 XML 标签的哈希表中为您提供向量 vec 中的数据。

于 2012-08-11T12:23:14.043 回答