6

我想知道如何在 BlackBerry 上解析 XML 数据。

我在某处读到 JSON 是解析 xml 数据的好方法。

是否有使用 JSON 或任何其他机制解析 XML 数据的教程?

4

4 回答 4

12

在黑莓中解析 XML

Simple API for XML (SAX) 是由公共邮件列表 (XML-DEV) 的成员开发的。它提供了一种基于事件的 XML 解析方法。这意味着它不是从一个节点到另一个节点,而是从一个事件到另一个事件。SAX 是一个事件驱动的接口。事件包括 XML 标记、检测错误等,J2ME SAX - 请参阅BlackBerry/J2ME - SAX 解析具有属性的对象集合

XML pull parser - 它最适合需要快速和小型 XML 解析器的应用程序。当必须快速有效地执行所有过程以输入元素时,应该使用它 kXML - J2ME 拉解析器 - 请参阅Blackberry 中 XML 创建的更好方法

使用 JSON 解析 XML

用于 JSON 解析的黑莓标准是JSON ME

不知道... JSON 可以作为 XML 表示和传输,但反之则不行。

XML(可扩展标记语言)是一组以电子方式对文档进行编码的规则。它在 W3C 产生的 XML 1.0 规范和其他几个相关规范中定义,都是免费的开放标准。

XML 示例:

<?xml version="1.0" encoding='UTF-8'?>
<painting>
  <img src="madonna.jpg" alt='Foligno Madonna, by Raphael'/>
  <caption>This is Raphael's "Foligno" Madonna, painted in
    <date>1511</date>–&lt;date>1512</date>.
  </caption>
</painting>

JSON(JavaScript Object Notation 的首字母缩写词)是一种轻量级的基于文本的开放标准,专为人类可读的数据交换而设计。它源自 JavaScript 编程语言,用于表示简单的数据结构和关联数组,称为对象(“JSON”中的“O”)。尽管它与 JavaScript 有关系,但它是独立于语言的,几乎所有编程语言都有解析器。

JSON 示例:

{
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": "10021"
     },
     "phoneNumber": [
         { "type": "home", "number": "212 555-1234" },
         { "type": "fax", "number": "646 555-4567" }
     ]
 }

基本上,如果您的 XML 是 JSON 的强大等价物,例如:

<Person>
  <firstName>John</firstName>
  <lastName>Smith</lastName>
  <age>25</age>
  <address>
    <streetAddress>21 2nd Street</streetAddress>
    <city>New York</city>
    <state>NY</state>
    <postalCode>10021</postalCode>
  </address>
  <phoneNumber type="home">212 555-1234</phoneNumber>
  <phoneNumber type="fax">646 555-4567</phoneNumber>
</Person>

有可能用 JSON 解析这样的 XML。

于 2010-05-04T05:23:33.130 回答
3

解析通常使用可以加载到项目中的第 3 方库来完成。如果您使用 XML,我使用了一个名为 kXML 解析器的库。设置它可能会很痛苦,但这里有关于如何设置的说明 -

http://supportforums.blackberry.com/t5/Java-Development/Tutorial-How-To-Use-3rd-Party-Libraries-in-your-Applications/mp/177543

http://www.craigagreen.com/index.php?/Blog/blackberry-and-net-webservice-tutorial-part-1.html

使用 kXML 非常简单。本教程在这里解释了如何解析 XML 文件 -

http://www.roseindia.net/j2me/kxml/j2me-xml-parser.shtml

编辑:哎呀,下一篇文章中的第一个教程对 kxml2 上的 xml 解析进行了非常全面的概述。所以我的帖子有点多余。

于 2010-05-04T15:03:01.933 回答
2
/**
 * class is used to parse the XML response from the server
 */
package com.rtcf.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import net.rim.device.api.i18n.DateFormat;
import net.rim.device.api.i18n.SimpleDateFormat;
import net.rim.device.api.xml.parsers.ParserConfigurationException;
import net.rim.device.api.xml.parsers.SAXParser;
import net.rim.device.api.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.rtcf.bean.ItemBean;
import com.rtcf.bean.SpvItemBean;

import com.rtcf.bean.ItemCategoryMappingsBean;
import com.rtcf.screen.FirstSyncProgressScreen;
import com.rtcf.util.db.SQLManagerSync1;


public class ItemXMLParser extends DefaultHandler  {

    //private Statement statement = null;   
    public int currentpage = 1, totalpage = 1;
    public int maxWidth; 

    private final int BATCH_COUNT = 100;

    private String tempVal;

    long startT, endT;
    private Vector vecItem = new Vector(BATCH_COUNT);
    private Vector vecItemCategoryMapping = new Vector(BATCH_COUNT);

    //constructor
    int roomInsCount = 0;
    int roomMapInsCount = 0;

    int TBL_FACILITYCount = 0;
    int insCount = 0;

    private FirstSyncProgressScreen fsps;
    private SQLManagerSync1 tempDb;

    //constructor   
    public ItemXMLParser(FirstSyncProgressScreen fsps, SQLManagerSync1 tempDb){
        this.fsps=fsps;
        this.tempDb = tempDb;
        getData();
    }

    /**
     * Method returns the list of data in a vector (response objects) 
     * @param url
     * @return Vector
     */
    public void getData(){

        FileConnection fconn = null;
        InputStream inputStream = null;     

        try{

            // String url = "http://10.10.1.10/LDS/abcd.xml";
            // Logger.debug("HttpConParamUtil.getWebData -------------------- "+url);
             // HttpConParamUtil.getWebData(url, param, this, method);
             // HttpConUtilSingle.getWebData(url, this);
            //Logger.debug("response size -------------- "+response.size());


            String fileUrl = "file:///SDCard/Item.xml";
            fconn = (FileConnection)Connector.open( fileUrl, Connector.READ);


            //get a factory
            SAXParserFactory spf = SAXParserFactory.newInstance();

            try {

                inputStream = fconn.openInputStream();              

                //get a new instance of parser
                SAXParser sp = spf.newSAXParser();

                //parse the file and also register this class for call backs
                sp.parse(inputStream, this);

            }catch(SAXException se) {
                Logger.error( "  startDocument "+se.getMessage(), se);          

            }catch (IOException ie) {
                Logger.error( "  startDocument "+ie, ie);           

            } catch (ParserConfigurationException e) {
                // TODO Auto-generated catch block
                Logger.error( "  startDocument "+e, e);         

            } catch (Exception e) {
                // TODO Auto-generated catch block
                Logger.error( "  "+e, e);           

            }

        }
        catch (Exception e) {
            //Logger.debug("### Exception in getData - "+e.getMessage()+" "+e.getClass());
            //Dialog.inform("### Exception in getData - "+e.getMessage()+" "+e.getClass());
        }finally{

            try{
                if(inputStream != null){inputStream.close(); }
            }catch(Exception e){}           

            try{
                if(fconn != null){fconn.close(); }
            }catch(Exception e){}
        }
        //return response;
    }// end getData

     //===========================================================
    // Methods in SAX DocumentHandler 
    //===========================================================

     public void startDocument () throws SAXException{
         //Logger.debug("################# In startDocument");
            DateFormat timeFormat = new SimpleDateFormat("HH.mm.ss");
            startT = System.currentTimeMillis();

            // String currentTime = timeFormat.format(date);
            Logger.debug("########## ----------Start time:" + startT);


     }

     public void endDocument () throws SAXException{

         if( vecItemCategoryMapping.size() > 0){
             //fsps.updatedProgress2(22, "Inserting TBL_ITEM_CATEGORY_MAPPING Record ");
                Logger.debug("Populate TBL_ITEM_CATEGORY_MAPPING...");
                tempDb.InsertTbl_item_category_mapping(vecItemCategoryMapping);
                vecItemCategoryMapping = null;
                //vecItemCategory = new Vector(BATCH_COUNT);

            }
         if( vecItem.size() > 0){
            // fsps.updatedProgress2(25, "Inserting TBL_ITEM Record ");
                Logger.debug("Populate TBL_ITEM...");
                tempDb.InsertTbl_item(vecItem);
                vecItem = null;
                //vecItem = new Vector(BATCH_COUNT);

            }

     }

     //Event Handlers
     public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
         //Logger.debug("################# In startElement qName : "+qName);

            if(qName.equals("TBL_ITEM_CATEGORY_MAPPING")){
                Logger.debug("Populate TBL_ITEM_CATEGORY_MAPPING...");
                populateTblItemCategoryMapping(attributes);
            }
            if(qName.equals("TBL_ITEM")){
                Logger.debug("Populate TBL_ITEM...");
                populateTblItem(attributes);
            }

     }



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

            if(qName.equals("TBL_ITEM_CATEGORY_MAPPING")&& vecItemCategoryMapping.size() == BATCH_COUNT){
                Logger.debug("Populate TBL_ITEM_CATEGORY...");
                tempDb.InsertTbl_item_category_mapping(vecItemCategoryMapping);
                vecItemCategoryMapping = null;
                vecItemCategoryMapping = new Vector(BATCH_COUNT);

            }
            if(qName.equals("TBL_ITEM")&& vecItem.size() == BATCH_COUNT){
                Logger.debug("Populate TBL_ITEM...");
                tempDb.InsertTbl_item(vecItem);
                vecItem = null;
                vecItem = new Vector(BATCH_COUNT);

            }
        }


    public void characters(char[] ch, int start, int length) throws SAXException {
        //Logger.debug("################# In characters");
        tempVal = new String(ch,start,length);
    }


     // reads the xml file and saves the ItemCategoryMappingBean data and adds to vecItemCategoryMapping

    private void populateTblItemCategoryMapping(Attributes attributes) {

        try{
            ItemCategoryMappingsBean ItemCategoryMappingBean = new ItemCategoryMappingsBean();

                try{
                    if((attributes.getValue("itemCategoryId"))!=null)
                    ItemCategoryMappingBean.itemCategoryId = Integer.parseInt(attributes.getValue("itemCategoryId"));
                    else {
                        ItemCategoryMappingBean.itemCategoryId = -1;
                    }
                    if((attributes.getValue("itemId"))!= null)
                    ItemCategoryMappingBean.itemId = Integer.parseInt(attributes.getValue("itemId"));
                    else {
                        ItemCategoryMappingBean.itemId = -1;
                    }

                    if((attributes.getValue("ddlFlag"))!=null) 
                        ItemCategoryMappingBean.ddlFlag = attributes.getValue("ddlFlag").charAt(0);
                        else {
                            ItemCategoryMappingBean.ddlFlag = 'I';
                        }

                    //ItemCategoryMappingBean.categoryName = (attributes.getValue("categoryName"));
                    Logger.debug("#######  populateTblItemCategoryMapping ");
                }catch(NumberFormatException nfe){
                    Logger.error("### NumberFormatException SAXXMLParser -->> populateTblItemCategoryMapping() - "+nfe.getMessage(),nfe);
                                    }
                vecItemCategoryMapping.addElement(ItemCategoryMappingBean);

        }catch(Exception e){
            Logger.error("ItemXMLParser -->> populate  TblItemCategory() - "+e.getMessage(),e);
            }   

    }


    // reads the xml file and saves the ItemBean data and adds to vecItem

    private void populateTblItem(Attributes attributes) {
        // TODO Auto-generated method stub
        ItemBean itemBean= new ItemBean();
        try{

        try{

            itemBean.itemId = Integer.parseInt(attributes.getValue("itemId"));

            if((attributes.getValue("videoURL"))!=null)
            itemBean.videoURL = (attributes.getValue("videoURL"));
            else {
                itemBean.videoURL = "";
            }


            if((attributes.getValue("itemDescription"))!=null)
            itemBean.itemDescription = (attributes.getValue("itemDescription"));
            else {
                itemBean.itemDescription = "";
            }

            if((attributes.getValue("itemProcedure"))!=null)
            itemBean.itemProcedure = (attributes.getValue("itemProcedure"));
            else {
                itemBean.itemProcedure = "";
            }

            if((attributes. getValue("itemStandard"))!=null)
            itemBean.itemStandard = (attributes.getValue("itemStandard"));
            else {
                itemBean.itemStandard = "";
            }

            if((attributes.getValue("weight"))!=null)
            itemBean.weight = (attributes.getValue("weight"));
            else {
                itemBean.weight = "";
            }

            if((attributes.getValue("ddlFlag"))!=null) 
                itemBean.ddlFlag = attributes.getValue("ddlFlag").charAt(0);
                else {
                    itemBean.ddlFlag = 'I';
                }

            vecItem.addElement(itemBean);
            Logger.debug("#######  populate  TblItem ");
        }catch(NumberFormatException nfe){
            Logger.error("### NumberFormatException SAXXMLParser -->> populateTblItemCategoryMapping() - "+nfe.getMessage(),nfe);
                            }


}catch(Exception e){
    Logger.error("ItemXMLParser -->> populateTblItemCategory() - "+e.getMessage(),e);
    }   
    }


}// end XMLParser
于 2011-05-13T09:53:51.473 回答
2

此链接来自黑莓网站: http ://www.blackberry.com/knowledgecenterpublic/livelink.exe/fetch/2000/348583/800332/800599/How_To_-_Use_the_XML_Parser.html?nodeid=820554&vernum=0

我进行了以下更改以使其正常工作(是的...BB开发网站有时很烦人..)

在方法 updateField() - 确保添加 ui 线程,否则不会发生变化。

 UiApplication.getUiApplication().invokeLater(new Runnable() 
    {
        public void run()
        {
             String title="Title";
                _screen.add(new RichTextField(node+" : "+element));

                if(node.equals(title))
                {
                    _screen.add(new SeparatorField());
                }
        }
    });

此外,如果您想在本地读取 .xml 文件(例如在您的文件夹中) - 您显然不需要与端口的 localhost 连接。无论哪种方式,当我使用 local://test.xml 运行它时,我一直收到连接错误。去论坛跳转,找到了这个小解决方案。(是的,我的 .xml 文件称为 madhouse)。哦,“test.xml.XMLDemoScreen - 是包名和类名。

Class cl = Class.forName("test.xml.XMLDemoScreen");
InputStream in = cl.getResourceAsStream("/madhouse.xml");
doc = docBuilder.parse(in);

希望有帮助!:D

于 2012-06-22T18:20:53.893 回答