package Lession1;import java.io.File;
import java.util.List;import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;public class XMLPrase { /**
* @param args
* @throws DocumentException
*/
public static void main(String[] args) throws DocumentException {
// TODO Auto-generated method stub
File file=new File("D:\\workspace1\\com.chenyili\\src\\Lession1\\students.xml");
SAXReader reader=new SAXReader();
Document doc=reader.read(file);
//得到根节点
Element root =doc.getRootElement();
System.out.println("<"+root.getName()+">");
List<Element> list=root.elements();
//遍历根节点元素
for(Element ele:list){
System.out.println("\t<"+ele.getName()+">");
//取得第一个节点属性
Attribute att=ele.attribute(0);
System.out.print(att.getName() + "='" + att.getValue() + "'"); List<Element> eles=ele.elements();
//遍历节点的属性
for(Element e:eles){
System.out.println("\t\t<"+e.getName()+">");
String Value=e.getText();
System.out.println(Value);
System.out.println("\t</"+e.getName()+">");
}
System.out.println("\t</"+ele.getName()+">");
}
System.out.println("</"+root.getName()+">");
}}<?xml version="1.0" encoding="UTF-8"?><students>
<student>
<name>Mike</name>
<age>23</age>
</student>
<student>
<name>Rose</name>
<age>22</age>
</student>
</students>
报错信息:
Exception in thread "main" java.lang.NullPointerException
at Lession1.XMLPrase.main(XMLPrase.java:29)
<students>
<student>
去掉红色的字段就可以正常运行,但是那两个值为什么就打印不出来?
DOM解析XML
System.out.print(att.getName() + "='" + att.getValue() + "'"); 这个试改成这个
System.out.print(att.getName() + "=" + att.getValue() );
但是最根本的原因是你的任何一个标签都没有属性 ,所以你当然取不到任何 attribute,强烈建议你去看下XML文档的格式知识。