最近想学习一下XML读取的操作。我会把各种读取XML的方法写成程序。希望大家给点意见。XML文件
读取XML文件,使用的DOM
<?xml version="1.0" encoding="gb2312"?>
<?xml-stylesheet type="text/xsl" href="students.xsl"?>
<students>
<student sn="01">
<name>张三</name>
<age>18</age>
</student>
<student sn="02">
<name>李四</name>
<age>20</age>
</student>
</students>
读取XML文件,使用的DOM
package com.ibm.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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* DOM解析XML
* 通过获取子节点方法
* @author Administrator
*
*/
public class DOMStudentsInfo {
/**
* @param args
*/
public static void main(String[] args) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
System.out.println(dbf.getClass().getName());
try {
DocumentBuilder db=dbf.newDocumentBuilder();
//读取文件
Document doc=db.parse(new File("students.xml"));
//获取子节点
NodeList nl=doc.getElementsByTagName("student");
int len=nl.getLength();
//获取节点数
System.out.println(len);
for(int i=0;i<len;i++)
{
Element eltStu=(Element)nl.item(i);
Node eltName=eltStu.getElementsByTagName("name").item(0);
Node eltAge=eltStu.getElementsByTagName("age").item(0);
String name=eltName.getFirstChild().getNodeValue();
String age=eltAge.getFirstChild().getNodeValue();
System.out.println("name: "+name);
System.out.println("age: "+age);
System.out.println("-------------------------");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
}catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}