java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

java解析XML

java解析XML有很多方式,dom4j jdom等等。
今天发现org.w3c.dom 是java自带的类包。而且比较简单

/*
java解析XML,读取xml中的书名和作者
*/
package com.javaer.examples.file;

import java.io.File;

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

import org.w3c.dom.*;

public class ReadXML {

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = factory.newDocumentBuilder();
		Document doc = db.parse(new File("/Users/mc2/WEB/JSP/Javaer/x1.xml"));
		Element elmtInfo = doc.getDocumentElement();
		NodeList nodes = elmtInfo.getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				// System.out.println(node.getNodeName());
				NodeList nodes2 = node.getChildNodes();
				for (int j = 0; j < nodes2.getLength(); j++) {
					Node node2 = nodes2.item(j);
					if (node2.getNodeType() == Node.ELEMENT_NODE) {
						System.out.println(node2.getNodeName() + " : "
								+ node2.getTextContent());
					}
				}
			}
		}
		
		
	}

}

xml


	
		English study
		James.bangding
	
	
		Gargon Goyui
		Tomas.Tang
	

执行结果
name : English study
author : James.bangding
name : Gargon Goyui
author : Tomas.Tang


This entry was posted in JAVA and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-parse-xml/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply