解析xml基本操作类

java代码
package test;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
 
/**
 * @author ybc
 *
 */
public class FileTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		FileTest test = new FileTest();
		test.testFile();
		
	}
	
	public void testFile() {
		String filename = "E:\\data\\xmldata\\ybc.xml";
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	  	DocumentBuilder db= null;
	  	Document doc = null;
		try {
	  		db = dbf.newDocumentBuilder();
	  		doc = db.parse(filename);
	  	} catch (Exception e) {
			System.out.println("打开文件错误:" + filename);
			e.printStackTrace();
			return;
		}	

	  	Element root = doc.getDocumentElement();
		System.out.println("XML解析成功");
		
		NodeList ybcList = root.getElementsByTagName("ybc");

		for (int i = 0; i < ybcList.getLength(); i++) {
			Element report = (Element) ybcList.item(i);// 返回一个Node

		 			String name=report.getAttribute("name").trim();  
			String age=report.getAttribute("age");
			String address=report.getAttribute("address");
			System.out.println(name+"||"+age+"||"+address);
		}
	}
	 
}

xml文件(E:\\data\\xmldata\\ybc.xml):
引用
<?xml version="1.0" encoding="GB2312" ?>
- <ybcs>
  <ybc name="bcyin" age="27" address="白下 路" />
  </ybcs>


运行结果:
XML解析成功
bcyin||27  ||白下  路

你可能感兴趣的:(xml)