java解析XML dom方式

阅读更多
    /** 
     * @param args 
     */  
    public static void main(String[] args) {  
        // try {  
        // HelloStub stub = new HelloStub();  
        // GetUser user = new GetUser();  
        // user.setId("22");  
        // stub.getUser(user);  
        // } catch (AxisFault e) {  
        // // TODO Auto-generated catch block  
        // e.printStackTrace();  
        // } catch (RemoteException e) {  
        // // TODO Auto-generated catch block  
        // e.printStackTrace();  
        // }  
        String xml = ""  
                + ""  
                + ""  
                + ""  
                + " "  
                + "     0"  
                + "     hello" + "       "  
                + "" + ""  
                + "";  
        Map> map = new HashMap>();  
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        try {  
            DocumentBuilder db = dbf.newDocumentBuilder();  
            ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());  
            Document document = db.parse(is);  
            NodeList node = document.getChildNodes();  
            Test test = new Test();  
            for (int i = 0; i < node.getLength(); i++) {  
                   
                Node a = node.item(i);  
                if(a instanceof DeferredElementImpl)  
                {  
                    test.pars(a, map);  
                }  
            }  
        } catch (ParserConfigurationException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (SAXException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        //System.out.println(map.get("code").get(0).getTextContent());  
       
    }  
       
    public void pars(Node node, Map> map)  
    {  
        NodeList nodeList = node.getChildNodes();  
        if(node instanceof DeferredElementImpl)  
        {  
            String name = node.getNodeName().split(":")[1];  
            if (map.get(name) != null) {  
                map.get(name).add(node);  
                   
            } else {  
                List l = new ArrayList();  
                l.add(node);  
                map.put(name, l);  
            }  
        }  
        if (nodeList == null || nodeList.getLength() == 0) {  
            return;  
        } else {  
            for (int i = 0; i < nodeList.getLength(); i++) {  
                Node n = nodeList.item(i);  
                if(n instanceof DeferredElementImpl)  
                {  
                pars(n, map);  
                }  
            }  
        }  
    }  

你可能感兴趣的:(java,XML)