`
landyer
  • 浏览: 139495 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Android DOM 解析 xml

 
阅读更多

原文地址:http://blog.163.com/joe_zhpf@126/blog/static/81331086201041271841759/

 

 

解析xml后返回一个 hashmap.  
形成 key - value
                  value-( ArrayList )->
                                               ListItem(HashMap(key, value))
如果value是个list.则每个list item.又是一个键值对.  如果每个item的value含有多个值,则用
自定义类的 SingleItem来保存.   每个SingleItem 包含一个 hashMap.
如果每个 item value是多个child.则list里面放置着多个Singltem.
可以无限循环.

 

 

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class Utills {
    private static final String TAG = Utills.class.getSimpleName();
    public static final boolean DEBUG_FLAG = true;
    public static final String ILLIGAL_FLAG = "#text";
    
    /**
     * only set for a node. the node hasn't any child node.
     * @param node
     * @return
     */
    public static SingleItem parseNodeAttributes(Node node){
            NamedNodeMap nameMap = node.getAttributes();
            int mapLength = nameMap.getLength();
            SingleItem  singleItem = new SingleItem();
            
            // match for <key><key> 
            if(mapLength == 0){
                singleItem.addAttribute(node.getNodeName(), "");
                return singleItem;
            }
            //fill the node attribute to a item of the list
            for(int nameIndex = 0; nameIndex < mapLength;nameIndex++){
                Node temp = nameMap.item(nameIndex);
                singleItem.addAttribute(temp.getNodeName(),temp.getNodeValue());
            }
        return singleItem;
    }
    
    /**
     * 
     * @param node
     * @param container
     * @param singleItems
     */
    public static void parseNode(Node node,HashMap<String,Object> container,ArrayList<SingleItem> singleItems){
        if(node.hasChildNodes()){
            NodeList nodeList = node.getChildNodes();
            int childLength = nodeList.getLength();
            //this code for parse <key>value</key>
            if(childLength ==1){
                if(singleItems == null){
                    // if this is the top elements, put it to the map.
                    container.put(node.getNodeName(), nodeList.item(0).getNodeValue());
                }else{
                    // if it not the top element, save it as the SingItem
                    SingleItem  singleItem = new SingleItem();
                    singleItem.addAttribute(node.getNodeName(), nodeList.item(0).getNodeValue());
                    singleItems.add(singleItem);
                }
                return;
            }
            Node nodeTemp;
            ArrayList<SingleItem> singleItesList;
             singleItesList = new ArrayList<SingleItem>();
            
            //add Item to a list.
            for(int i =0; i < childLength; i++){
                nodeTemp = nodeList.item(i);
                if(nodeTemp.getNodeType() == Node.TEXT_NODE  ){
                    continue;
                }
                parseNode(nodeList.item(i), null,singleItesList);
            }
            
            if(container == null){
                singleItems.add(new SingleItem(node.getNodeName(),singleItesList));
            }else{
                container.put(node.getNodeName(), singleItesList);
            }
            
            nodeTemp = null;
        }else{
            //  parse <key> <key2 name=10/></key>
            if(singleItems == null){
                container.put(node.getNodeName(), parseNodeAttributes(node));
            }else{
                singleItems.add(parseNodeAttributes(node));
            }
        }
    }

    /**
     * 
     * @param inputStream
     * @return
     */
    public static  HashMap<String,Object> parseXML(InputStream inputStream ) {
        HashMap<String,Object> items = new HashMap<String,Object>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        //TODO:  需要格式验证不?
        try {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        Document dom = null;
        try {
             dom = builder.parse(inputStream);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
          Element root = dom.getDocumentElement();
          parseNode(root, items, null);
        return items;
    }
}

 

 

import java.util.HashMap;
import java.util.Set;

public class SingleItem {
    private HashMap<String,Object> content = new HashMap<String,Object>();
    
    /**
     * 
     */
    public SingleItem() {
    }
    
    /**
     * constructer
     * @param key
     * @param value
     */
    public SingleItem(String key, Object value) {
        this.addAttribute(key, value);
    }
    
    /**
     * Add an attribute to the item.If item has this key,return false;
     * @param key
     * @param value
     * @return
     */
    public boolean addAttribute(String key, Object value){
        if(content.containsKey(key)){
            return false;
        }
        
        content.put(key, value);
        return true;
    }
    
    /**
     * Update an attribute .If item contains this key,update the value 
     * return true,if not return false.
     * @param key
     * @param value
     * @return
     */
    public boolean updateAttribute(String key, Object value){
        if(content.containsKey(key)){
            content.put(key, value);
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        Set<String> sets = content.keySet();
        StringBuilder builder = new StringBuilder("{");
        for(Object key: sets){
            builder.append("["+key+" = "+content.get(key)+"]");
        }
        return builder.toString()+"}";
    }
}
 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics