XML和JSON字符串的解析,是Java程序猿的必备技能,关于XML和JSON如何解析,网上的例子可以说是一拉一大把,解析JSON的有什么GSON、json-lib等一大批做得非常好的第三方工具,解析XML的也有什么DOM4J、JDOM、SAX、DOM等等,今天大桥就给大家展示一下如何有JDK自己解析XML,废话不多说,代码如下:


package cn.bridgeli.parsexmldemo.parsexml;

import java.io.FileNotFoundException;
import java.io.IOException;

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

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

public class ParseXml {

    public void parserXml(String fileName) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(fileName);
            NodeList rootNode = document.getChildNodes();

            parseNode(rootNode.item(0));

        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (ParserConfigurationException e) {
            System.out.println(e.getMessage());
        } catch (SAXException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public void parseNode(Node node) {
        if (node == null) {
            return;
        }

// if not have child  
        if (!node.hasChildNodes()) {

            NamedNodeMap attrs = node.getAttributes();
            if (attrs != null) {
                for (int i = 0; i < attrs.getLength(); i++) {
                    Attr attribute = (Attr) attrs.item(i);
                    System.out.print("AttributeName===" + attribute.getName() + " AttributeValue===" + attribute.getValue());
                }
            }
            String str = node.getTextContent().toString().replaceAll("n", "").replaceAll(" ", "");
            if (!str.equals("")) {
                System.out.println("TextContent ===" + str);
            }
        } else {
// get attributes  
            NamedNodeMap attrs = node.getAttributes();
            if (attrs != null) {
                for (int i = 0; i < attrs.getLength(); i++) {
                    Attr attribute = (Attr) attrs.item(i);
                    System.out.println("AttributeName===" + attribute.getName() + " AttributeValue===" + attribute.getValue());
                }
            }

// get child node  
            NodeList nodes = node.getChildNodes();
            for (int j = 0; j < nodes.getLength(); j++) {
                parseNode(nodes.item(j));
            }
        }

    }
}

具体可以参考:

https://www.ibm.com/developerworks/cn/xml/x-jdom/

http://developer.51cto.com/art/200903/117512.htm

后记:

看完这篇文章,再加上之间的,大家是不是自己就可以模拟出Spring的IOC了?其实也很简单,有机会我会自己写一篇出来