package xuboTest;
import java.io.File;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlFileOperateAction {
private static final Log log = LogFactory.getLog(XmlFileOperateAction.class);
@SuppressWarnings("unchecked")
public static void main(String args[]){
String filePath2 = System.getProperty("user.dir")+"/WebContent/modules/student.xml";
SAXReader reader = new SAXReader();
Document document;
try {
document = reader.read(new File(filePath2));
Element root = document.getRootElement();
printData(root);
} catch (DocumentException e) {
log.error("出错了,麻痹的", e);
}
}
@SuppressWarnings("unchecked")
private static void printData(Element e){
//打印自己的数据
if(e.isRootElement()){
System.out.println(e.getName()+" : ");
}else{
System.out.println(e.getName()+" : "+e.getText());
}
List<Attribute> attributs = e.attributes();
for(Attribute attr : attributs){
System.out.println("*******"+attr.getName()+":"+attr.getValue());
}
//如果有子节点,就循环子节点
List<Element> elements = e.elements();
if(elements.size()>0){
for(Element ex : elements){
printData(ex);
}
}
}
}
import java.io.File;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class XmlFileOperateAction {
private static final Log log = LogFactory.getLog(XmlFileOperateAction.class);
@SuppressWarnings("unchecked")
public static void main(String args[]){
String filePath2 = System.getProperty("user.dir")+"/WebContent/modules/student.xml";
SAXReader reader = new SAXReader();
Document document;
try {
document = reader.read(new File(filePath2));
Element root = document.getRootElement();
printData(root);
} catch (DocumentException e) {
log.error("出错了,麻痹的", e);
}
}
@SuppressWarnings("unchecked")
private static void printData(Element e){
//打印自己的数据
if(e.isRootElement()){
System.out.println(e.getName()+" : ");
}else{
System.out.println(e.getName()+" : "+e.getText());
}
List<Attribute> attributs = e.attributes();
for(Attribute attr : attributs){
System.out.println("*******"+attr.getName()+":"+attr.getValue());
}
//如果有子节点,就循环子节点
List<Element> elements = e.elements();
if(elements.size()>0){
for(Element ex : elements){
printData(ex);
}
}
}
}
本文介绍了一个使用Java编写的程序,该程序通过DOM4J库解析XML文件并打印出其元素名称、文本内容及属性信息。文章展示了如何读取指定路径下的XML文件,并递归地遍历所有元素。

被折叠的 条评论
为什么被折叠?



