黑莓之xmlParser

为了使用方便,简单封装了一个黑莓下的xml解析器,用来打包或者解析xml,以期抛砖引玉。

 

/*
 * xmlParser.java
 *
 * ? <your company here>, 2003-2005
 * Confidential and proprietary.
 */

package bbserver;

 

import java.io.*;
import java.util.*;
import net.rim.device.api.xml.parsers.*;
import org.w3c.dom.*;
import net.rim.device.api.xml.jaxp.*;
import net.rim.device.api.ui.component.Status;

/**
 *
 */
class xmlParser
{
    private Document m_document = null;
    private boolean m_bWriter = true;   
    private Hashtable m_nodeTable = new Hashtable(); //storage the all kinds info from usb
   
    static private String _tag = "<?xml version=/"1.0/"?>/n";
   
    public xmlParser()
    {
    }
   
    static public void removeXmltag(StringBuffer buf)//remove xml version tag
    {
        String str = buf.toString();
        int idx = str.indexOf("?>");
        if(idx != -1)
        {
            buf.delete(0,idx+3);
        }
    }
   
    static public void addXmltag(StringBuffer buf)//add xml version tag
    {
        String str = buf.toString();
        int idx = str.indexOf("?>");
        if(idx == -1)
        {
            buf.insert(0,_tag);
        }
    }
   
    public boolean InitCreate()//used for create xml
    {
        boolean bRet = false;
        m_bWriter = true; 
                 
        try
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();          
                    
            m_document = builder.newDocument();          
        }
        catch( Exception e )
        {
            System.out.println( e.toString() );
            bRet = false;
        }   
       
        return bRet;
    }
   
    public Element InitParser(byte[] data,int len)//used for parse xml
    {
        m_bWriter = false; 
       
        try
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
                     
            ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(data/*,0,len*/);               
            m_document = builder.parse( xmlInputStream );              
        }
        catch( Exception e )
        {
            System.out.println( e.toString() );
        }   
       
        return m_document.getDocumentElement();
    }
   
    private boolean InitXmlParser(boolean bWriter,byte[] data,Document doc)
    {
        boolean bRet = false;
        m_bWriter = bWriter; 
                 
        try
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
           
            if(m_bWriter)
            {          
                m_document = builder.newDocument();
            }
            else
            {
                ByteArrayInputStream xmlInputStream = new ByteArrayInputStream(data);               
                m_document = builder.parse( xmlInputStream );
            }
        }
        catch( Exception e )
        {
            System.out.println( e.toString() );
            bRet = false;
        }   
       
        return bRet;
    }    
   
    //create a node and set it's value
    public Element addXmlNode(Element parent,String label,int value)
    {
        StringBuffer buf = new StringBuffer();
        buf.append(value);
       
        return addXmlNode(parent,label,buf.toString());
    }
   
    public Element addXmlNode(Element parent,String label,String value)
    {
        Element node = null;
        if((value != null) && (m_document != null)&&(parent != null))
        {
            node = m_document.createElement(label);
           
            //Text text = m_document.createTextNode(value);           
           // node.setNodeValue(value);
          
           Text text = m_document.createTextNode(value);
            node.appendChild(text);
            parent.appendChild(node);
        }
        return null;
    }
   
    //create a empty node ,that only have a tag no value
    public Element addXmlTag(Element parent,String label,boolean bRoot)
    {
        Element node = null;
        if((label != null) && (m_document != null))
        {
            node = m_document.createElement(label);
           if(bRoot)
           {
                m_document.appendChild(node);
           }
           else
           {
               if(parent != null)
                    parent.appendChild(node);
               else
                    node = null;
           }
        }
        return node;
    }
   
    public  boolean setNodeAttribute(Element node,String attrLabel,String attrValue)
    {
        boolean bRet = false;
        if((attrLabel != null) && (attrValue != null) && (m_document != null)&&(node != null))
        {
            try
            {
               node.setAttribute("arrt","1234");
               bRet = true;
            }catch(DOMException e)
            {
               System.out.println( e.toString() );
            }
        }
        return bRet;
    }
   
    public String getNodeText(Element node)
    {
       String text = "";
       
        for(Node subNode = node.getFirstChild();subNode!=null;subNode=subNode.getNextSibling())
        {
            if(subNode.getNodeType()==Node.TEXT_NODE)
            {
                String str = subNode.getNodeValue();
                if(!str.equals("/n"))
                {
                    text = str;
                    break;
                }
            }
        }
       
         return text;
    }
   
    public String getChildNodeText(Element node,String child)
    {
       String text = "";
       
        for(Node subNode = node.getFirstChild();subNode!=null;subNode=subNode.getNextSibling())
        {
            String name = subNode.getNodeName();
            if(name.equals(child))
            {
                text = getNodeText((Element)subNode);
                break;
            }
        }
       
         return text;
    }
   
    public String getXMLString()
    {
        StringBuffer strXML = null;
        try
        {
            ByteArrayOutputStream ba2 = new ByteArrayOutputStream();
            XMLWriter writer2 = new XMLWriter( ba2 );
            writer2.setPrettyPrint();
            // "parse" the document
            DOMInternalRepresentation xmlDir2 = new DOMInternalRepresentation();
            xmlDir2.parse(m_document,writer2);
   
            byte bXml3[]=ba2.toByteArray();
            strXML = new StringBuffer(new String(bXml3));
            removeXmltag(strXML);
        }catch( Exception e )
        {
            System.out.println( e.toString() );
        }
       
        return strXML.toString();
    }
   
    public String GetValueFromTable(String key)
    {
        String str = (String) m_nodeTable.get(key);     
        if(str == null)
        {
            str = "";
        }
       
        return str;
    }
   
    public int GetIntValueFromTable(String key)
    {
        String str = (String) m_nodeTable.get(key);     
        if(str == null)
        {
            str = "";
        }
       
        return Integer.valueOf(str).intValue();
    }
   
    private void putNodeToTable(String node,String value)
    {
        if((node != null)&&(value != null))
        {
            m_nodeTable.put(node,value);
        }
    }
   
    public void clearNodeTable()
    {
        m_nodeTable.clear();
    }
   
    public int  nChildNode(Element node,String childName)
    {
        int count = 0;
       
        if ( node.getNodeType() == Node.ELEMENT_NODE )
        {         
            NodeList list = node.getChildNodes();
            int numChildren = list.getLength();
           
            for(int i=0;i<numChildren;i++)
            {
                Node sub = list.item( i );
                if(sub.getNodeType()==Node.ELEMENT_NODE)
                {                   
                    String name = sub.getNodeName();   
                    if(name.equals(childName))
                    {
                        count++;
                    }
                }               
            }       
        }
       
        return count;
    }
   
    public String GetChildNodeText( Element node,String childName,int idx)
    {
        Node child = GetChildNode(node,childName,idx);
        return getNodeText((Element)child);
    }
   
    public Node GetChildNode( Element node,String childName,int idx)
    {
        Node child = null;
        if ( node.getNodeType() == Node.ELEMENT_NODE )
        {         
            NodeList list = node.getChildNodes();
            int numChildren = list.getLength();
           
            int seek = 0;
            for(int i=0;i<numChildren;i++)
            {
                Node sub = list.item( i );
                if(sub.getNodeType()==Node.ELEMENT_NODE)
                {                   
                    String name = sub.getNodeName();   
                    String value = new String();
       
                    if(name.equals(childName))
                    {
                        if(idx == seek)
                        {
                            child = sub;
                            break;
                        }
                       
                        seek++;
                    }
                }               
            }       
        }
       
        return child;
    }
   
    public void GetAllNodeValue( Element node)
    {
        clearNodeTable();
       
        if ( node.getNodeType() == Node.ELEMENT_NODE )
        {         
            NodeList list = node.getChildNodes();
            int numChildren = list.getLength();
           
            for(int i=0;i<numChildren;i++)
            {
                Node sub = list.item( i );
                if(sub.getNodeType()==Node.ELEMENT_NODE)
                {
                    String name = sub.getNodeName();   
                    String value = new String();

                    value = getNodeText((Element)sub);    
                   
                    String str = (String) m_nodeTable.get(name);     
                    if(str != null)
                    {                       
                        str += xcDef.STRING_TOKEN + value;
                    }
                    else
                        str = value;
                   
                    putNodeToTable(name,str);                          
                }               
            }       
        }      
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值