67,515
社区成员
发帖
与我相关
我的任务
分享
package dom4j.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Test {
/**
* @param args
* @throws DocumentException
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException, DocumentException {
// TODO Auto-generated method stub
Document document=parse();
Element root=document.getRootElement();
java.util.List persons=root.elements("person");
System.out.println(persons.size());
for(java.util.Iterator i=root.elementIterator();i.hasNext();){
Element person=(Element)i.next();
Element name=person.element("name");
Element company=person.element("company");
Element school=person.element("school");
System.out.println("name="+name.getData()+",age="+name.attributeValue("age")+",sex="+name.attributeValue("sex"));
System.out.println("company="+company.getData()+",addr="+company.attributeValue("addr")+",othername="+company.attributeValue("othername"));
System.out.println("school="+school.getData()+",addr="+school.attributeValue("addr")+",master="+school.attributeValue("master"));
}
}
public static Document parse() throws DocumentException, FileNotFoundException {
SAXReader reader = new SAXReader();
FileInputStream in=new FileInputStream("persons.xml");
Document document = reader.read(in);
return document;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person>
<name age="24" sex="男">何良太 </name>
<company addr="浙江杭州西湖区黄姑山路3号" othername="永程科技股份公司">浙江西安交大龙山软件公司 </company>
<school addr="安徽省巢湖市" master="张三">巢湖学院 </school>
</person>
<person>
<name age="20" sex="女">张红燕 </name>
<company addr="北京市东城区四环外线" othername="中国移动">中国移动通信有限公司 </company>
<school addr="安徽省芜湖市" master="李四">安徽师范大学 </school>
</person>
</persons>