首页 > 代码库 > java加载XML文件并解析xml
java加载XML文件并解析xml
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new File("d://demo.xml"));
Element root = document.getRootElement();
List actions = root.elements("action");
for (int i = 0; i < actions.size(); i++) {
Element action = (Element) actions.get(i);
System.out.println("\n" + "action.path--->" + action.attributeValue("path"));
System.out.println("action.class--->" + action.attributeValue("class"));
List forwards = action.elements("forward");
for(int j=0;j<forwards.size();j++){
Element forward = (Element) forwards.get(j);
System.out.println("forward.name--->" + forward.attributeValue("name"));
System.out.println("forward.url--->" + forward.attributeValue("url"));
}
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new File("d://demo.xml"));
Element root = document.getRootElement();
List actions = root.elements("action");
for (int i = 0; i < actions.size(); i++) {
Element action = (Element) actions.get(i);
System.out.println("\n" + "action.path--->" + action.attributeValue("path"));
System.out.println("action.class--->" + action.attributeValue("class"));
List forwards = action.elements("forward");
for(int j=0;j<forwards.size();j++){
Element forward = (Element) forwards.get(j);
System.out.println("forward.name--->" + forward.attributeValue("name"));
System.out.println("forward.url--->" + forward.attributeValue("url"));
}
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<!--xml文件-->
<?xml version="1.0" encoding="UTF-8"?>
<actions>
<action path="/chen" class="com.demo.testCHEN">
<forward name="success" url="xiao-chen"/>
<forward name="fail" url="da-chen"/>
</action>
<action path="/bei" class="com.demo.testBEI">
<forward name="success" url="xiao-bei"/>
<forward name="fail" url="da-bei"/>
</action>
</actions>
运行结果:
action.path--->/chen
action.class--->com.demo.testCHEN
forward.name--->success
forward.url--->xiao-chen
forward.name--->fail
forward.url--->da-chen
action.path--->/bei
action.class--->com.demo.testBEI
forward.name--->success
forward.url--->xiao-bei
forward.name--->fail
forward.url--->da-bei
java加载XML文件并解析xml
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。