jdom解析xml
1.首先是xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<request>
<tasklist>
<task>
<taskname>TNT</taskname>
<sleeptime>120</sleeptime>
<user>admin</user>
<password>admin</password>
<inputpath>ftp1</inputpath>
<outpath>ftp2</outpath>
<excppath>ftp3</excppath>
<errorpath>ftp4</errorpath>
</task>
</tasklist>
<cachepath></cachepath>
<tasktime>100</tasktime>
</request>
2java解析代码
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class TaskEnvReader {
//第一种方法
public void readXmlToList(){
SAXBuilder sb = new SAXBuilder();
try {
//Document doc = sb.build(this.getClass().getClassLoader().getResourceAsStream("env.xml"));
InputStream file = new FileInputStream("src/env.xml");
Document doc = sb.build(file);
Element root = doc.getRootElement();
Element root1 = root.getChild("tasklist");
List list = root1.getChildren("task");
for(int i=0; i<list.size(); i++){
Element element = (Element)list.get(i);
String taskname = element.getChildText("taskname");
String sleeptime = element.getChildText("sleeptime");
String password = element.getChildText("password");
System.out.println(taskname+" "+sleeptime+" "+password);
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//第二种方法
/* public void readXml() throws JDOMException, IOException{
SAXBuilder builder = new SAXBuilder();
InputStream file = new FileInputStream("src/xml/po.xml");
Document document = builder.build(file);//获得文档对象
Element root = document.getRootElement();//获得根节点
Element root1 = root.getChild("tasklist");
List list = root1.getChildren();
for(Element e:list) {
System.out.println("ID="+e.getAttributeValue("id"));
System.out.println("username="+e.getChildText("username"));
System.out.println("password="+e.getChildText("password"));
}
}*/
public static void main(String[] args) {
new TaskEnvReader().readXmlToList();
}
补充:Web开发 , 其他 ,