DOM解析.1

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;


public class student {
public static void main(String [] args)
{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db=dbf.newDocumentBuilder();
Document doc=db.parse(new File("student.xml"));
NodeList dl=doc.getElementsByTagName("student");
for(int i=0;i<dl.getLength();i++)
{
Element elt=(Element)dl.item(i);
Node eltName=(Node)elt.getElementsByTagName("name").item(0);
Node eltAge=(Node)elt.getElementsByTagName("age").item(0);
String name=eltName.getFirstChild().getNodeValue();
String age=eltAge.getFirstChild().getNodeValue();
System.out.println("name\t"+name+"\tage\t"+age+"\n");
}
} catch (ParserConfigurationException e) { e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
}
}
}
///////////////
对应的 xml
<?xml version="1.0" encoding="Gb2312"?>
<students>
<student ar="01">
<name>张三</name>
<age>18</age>
</student>
<student ar="02">
<name>李四</name>
<age>19</age>
</student>
</students>

你可能感兴趣的:(java,xml)