`

读取XML文件

    博客分类:
  • xml
阅读更多
引用

<?xml version="1.0" encoding="UTF-8"?>
<students>
	<!--student:id,name,class  -->
	<student>
		<id>001</id>
		<name>张三</name>
		<class>IBM08001</class>
	</student>
	<student>
		<id>002</id>
		<name>李斯</name>
		<class>IBM08001</class>
	</student>	
	<student>
		<id>003</id>
		<name>王五</name>
		<class>IBM08001</class>
	</student>	
	<student>
		<id>004</id>
		<name>赵六</name>
		<class>IBM08001</class>
	</student>	
</students>

package com.java.xml;

import java.io.File;
import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class GetXml {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		getInfoFromXML();
	}

	public static void getInfoFromXML() throws ParserConfigurationException, SAXException, IOException {
		File f = new File("/home/soft22/workspace/javatest/src/student.xml");
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(f);
		NodeList node = doc.getElementsByTagName("student");
		for (int i = 0; i < node.getLength(); i++) {
			System.out.println("学生ID:"+
					doc.getElementsByTagName("id").item(i).
getFirstChild().getNodeValue());
			System.out.println("姓名:"+
					doc.getElementsByTagName("name").item(i).
getFirstChild().getNodeValue());
			System.out.println("班级:"+
					doc.getElementsByTagName("class").item(i).
getFirstChild().getNodeValue());
		}
	}

}


显示结果:
学生ID:001
姓名:张三
班级:IBM08001
学生ID:002
姓名:李斯
班级:IBM08001
学生ID:003
姓名:王五
班级:IBM08001
学生ID:004
姓名:赵六
班级:IBM08001

分享到:
评论
1 楼 jie523314 2010-08-19  
  学习下。。。
发表评论

文章已被作者锁定,不允许评论。

相关推荐

Global site tag (gtag.js) - Google Analytics