zoukankan      html  css  js  c++  java
  • 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();
    }
    }

  • 相关阅读:
    P2043 质因子分解
    CODE[VS] 3164 质因数分解
    借过
    CODE[VS] 1165 字符串的展开 || P1098 字符串的展开
    CODE[VS] 1144 守望者的逃离 || P1095 守望者的逃离
    CODE[VS] 2914 吹空调
    AC日记
    AC日记
    山科日记—回文
    山科日记—编写函数myFloor和myCeil(编程题)
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3125088.html
Copyright © 2011-2022 走看看