使用dom编辑xml节点示例代码,domxml节点示例代码,package cn.o
分享于 点击 47457 次 点评:6
使用dom编辑xml节点示例代码,domxml节点示例代码,package cn.o
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: nullFound Node: #text - with value: Found Node: channel - with value: nullFound Node: #text - with value: Found Node: title - with value: nullFound Node: #text - with value: Java Tutorials and ExamplesFound Node: #text - with value: Found Node: language - with value: nullFound Node: #text - with value: en-usFound Node: #text - with value: Found Node: item - with value: nullFound Node: #text - with value: Found Node: title - with value: nullFound Node: #cdata-section - with value: Java TutorialsFound Node: #text - with value: Found Node: link - with value: nullFound Node: #text - with value: http://www.javacodegeeks.com/Found Node: #text - with value: Found Node: #text - with value: Found Node: item - with value: nullFound Node: #text - with value: Found Node: title - with value: nullFound Node: #cdata-section - with value: Java ExamplesFound Node: #text - with value: Found Node: link - with value: nullFound Node: #text - with value: http://examples.javacodegeeks.com/Found Node: #text - with value: Found Node: #text - with value: Found Node: #text - with value:
用户点评