xml标签内的子元素的读取以及解析

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.FileInputStream;
import java.io.InputStream;

public class XMLParse {

public static void main(String[] args) throws Exception {
    InputStream InputStream = getInputStream("D:\\test2.xml");
    Element element = getElements(InputStream);
    getCertainElement(element);

}

private static InputStream getInputStream(String path) {
    InputStream inputStream = null;
    try {
        inputStream = new FileInputStream(path);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return inputStream;
}

private static Element getElements(InputStream inputStream) throws Exception {
    if (inputStream == null) {
        return null;
    }
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(inputStream);
    Element element = document.getDocumentElement();
    if (inputStream != null) {
        inputStream.close();
    }
    return element;
}

private static void getCertainElement(Element ele) {
    NodeList childNodes = ele.getChildNodes();
    NamedNodeMap attrs = ele.getAttributes();
    if (attrs != null && attrs.getLength() > 0) {
        for (int i = 0; i < attrs.getLength(); i++) {
            Attr item = (Attr) attrs.item(i);
            String name = item.getName();
            String value = item.getValue();
            System.out.println(name + "=" + value);
        }
    }
    if (childNodes != null && childNodes.getLength() > 0) {
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            if (node instanceof Element) {
                getCertainElement((Element) node);
            }
        }
    }
}

}

你可能感兴趣的:(xml标签内的子元素的读取以及解析)