返回顶部

收藏

使用dom编辑xml节点示例代码

更多
package cn.outofmemory.snippets.core;

import java.io.File;
import java.io.FileInputStream;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class VisitNodesInDOMDocumentRecursively {

    public static void main(String[] args) throws Exception {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document doc = db.parse(new FileInputStream(new File("in.xml")));

        visitRecursively(doc);

    }

    public static void visitRecursively(Node node) {

        // get all child nodes
        NodeList list = node.getChildNodes();

        for (int i=0; i<list.getLength(); i++) {

            // get child node
            Node childNode = list.item(i);

            System.out.println("Found Node: " + childNode.getNodeName()
                    + " - with value: " + childNode.getNodeValue());

            // visit child node
            visitRecursively(childNode);
        }

    }

}

Input:

<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
    <channel>
        <title>Java Tutorials and Examples</title>
        <language>en-us</language>
        <item>
            <title><![CDATA[Java Tutorials]]></title>
            <link>http://www.javacodegeeks.com/</link>
        </item>
        <item>
            <title><![CDATA[Java Examples]]></title>
            <link>http://examples.javacodegeeks.com/</link>
        </item>
    </channel>
</rss>

输出:

Found Node: rss - with value: null
Found Node: #text - with value: 

Found Node: channel - with value: null
Found Node: #text - with value: 

Found Node: title - with value: null
Found Node: #text - with value: Java Tutorials and Examples
Found Node: #text - with value: 

Found Node: language - with value: null
Found Node: #text - with value: en-us
Found Node: #text - with value: 

Found Node: item - with value: null
Found Node: #text - with value: 

Found Node: title - with value: null
Found Node: #cdata-section - with value: Java Tutorials
Found Node: #text - with value: 

Found Node: link - with value: null
Found Node: #text - with value: http://www.javacodegeeks.com/
Found Node: #text - with value: 

Found Node: #text - with value: 

Found Node: item - with value: null
Found Node: #text - with value: 

Found Node: title - with value: null
Found Node: #cdata-section - with value: Java Examples
Found Node: #text - with value: 

Found Node: link - with value: null
Found Node: #text - with value: http://examples.javacodegeeks.com/
Found Node: #text - with value: 

Found Node: #text - with value: 

Found Node: #text - with value: 

标签:java,xml

收藏

0人收藏

支持

0

反对

0