JDOM、DOM4J解析XML方式是在DOM的基础上完成的,都要导入特定jar包来获取API接口,是通过节点的层级关系来获取节点内容的。
1、JDOM 方式
导入jdom-2.0.5.jar
/**
*
* 用JDOM的方式解析XML文件
*
* */
public class JDOM_Parse {
public static void main(String[] args) {
//1、获取SAXBuilder对象
SAXBuilder builder=new SAXBuilder();
//2、创建一个输入流,加载xml文件
InputStream is;
try {
is=new FileInputStream("department.xml");
//3、创建Document对象
Document document=builder.build(is);
//4、获取根节点
Element rootElement=document.detachRootElement();
//5、获取所有子节点
List<Element> childElement=rootElement.getChildren();
for (Element element : childElement) {
//获取当前子节点的所有属性
List<Attribute> attributes=element.getAttributes();
for (Attribute attr : attributes) {
System.out.print(attr.getName()+": " +attr.getValue()+",");
}
System.out.println();
List<Element> childNode = element.getChildren();
for (Element node : childNode) {
System.out.println("节点名:"+node.getName()+" 节点值:"+node.getValue());
}
System.out.println();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2、DOM4J方式
导入dom4j-1.6.1.jar
public class DOM4J_parse {
public static void main(String[] args) {
SAXReader reader=new SAXReader();
try {
Document document = reader.read(new File("department.xml"));
Element rootElement = document.getRootElement();
Iterator it= rootElement.elementIterator();
while (it.hasNext()) {
Element element = (Element) it.next();
List<Attribute> attributes=element.attributes();
System.out.println();
for (Attribute attr : attributes) {
System.out.print("属性名:"+attr.getName()+" ==== 属性值:"+attr.getValue()+" , ");
}
Iterator childIt = element.elementIterator();
while (childIt.hasNext()) {
Element node = (Element) childIt.next();
System.out.println("节点名: "+node.getName()+" ----- 节点值: "+node.getText());
}
System.out.println();
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}