xml解析-jaxp遍历结点

jaxp遍历结点

把xml中所有的结点都打印出来
// 遍历结点把所有元素名称打印出来
/
1.创建解析器工厂
* 2.根据解析器工厂创建解析器
* 3.解析xml返回document
*
* 4.得到根节点
* 5.得到根节点的子节点
* 6.得到根节点子节点的子节点
* */

    public static void listElement() throws Exception{

        //创建解析器工厂
        DocumentBuilderFactory builderFactoty = DocumentBuilderFactory.newInstance();
        //创建解析器
        DocumentBuilder builder = builderFactoty.newDocumentBuilder();
        //解析xml返回document
        Document document = builder.parse("src/person.xml");
        
        //编写一个方法实现遍历操作
        list1(document);    
    }
    
    public static void list1(Node node)
    {
        if(node.getNodeType() == node.ELEMENT_NODE)
            System.out.println(node.getNodeName());
        //得到一层子节点
        NodeList lists= node.getChildNodes();
        for(int i=0;i!=lists.getLength();i++)
        {
            Node node1 = lists.item(i);
            list1(node1);
        }       
    }

猜你喜欢

转载自www.cnblogs.com/selfdef/p/11093668.html