当前位置 : 主页 > 编程语言 > c++ >

xml 解析(DOM)

来源:互联网 收集:自由互联 发布时间:2021-06-30
gistfile1.txt 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;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderF
gistfile1.txt
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;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;

/**
 * dom解析递归解析属性节点
 */
public class DomDemoLoopAttribute {
    public static void main(String[] args) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document parse = documentBuilder.parse(new File("D:\\IDEA\\ideawebworkspace\\xmlreview\\src\\user.xml"));

            NodeList childNodes = parse.getChildNodes();
            loopchilNodes(childNodes);

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void loopchilNodes(NodeList childNodes) {

        for (int i = 0; i < childNodes.getLength(); i++) {
            Node item = childNodes.item(i);
            if (item.getNodeType() == 3) {
                System.out.println(item.getNodeName() + "-" + item.getNodeType() + "-" + item.getNodeValue());

            } else if (item.getNodeType() == 1) {
                //获取属性节点
                loopAttributesNode(item);
                loopchilNodes(item.getChildNodes());


            }


        }
    }

    private static void loopAttributesNode(Node item) {
        NamedNodeMap attributes = item.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {

            Node item1 = attributes.item(i);
            System.out.println(item1.getNodeName() + " -" + item1.getNodeType() + "-" + item1.getNodeValue()
            );
        }
    }
}
网友评论