dom4j 和jdom

dom4j读取xml文件:

依赖于jar包: dom4j.jar 和 jaxen-1.1.1.jar
<?xml version="1.0" encoding="UTF-8"?>
<list>
 <index>D:\\index\\IndexDB</index>
</list>





package com.wlh.dom4j.test;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class TestReader {
	public static void main(String args[]){
		String filePath="index.xml";
		try {
			//如果配置文件是在Src下,则采用如下方式得到Document
			Document document=new SAXReader().read(Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath));
			//如果配置文件是在本地文件系统,则采用如下方式得到Document		
			//Document document=new SAXReader().read("D:\\index.xml");
			if (document == null) {   
                System.out.println(filePath+"没找到");   
            }else{  
			Node node=document.selectSingleNode("//list/index");
		    String indexfile=node.getText();
		    System.out.println(indexfile);
		   }
			} catch (DocumentException e) {
			e.printStackTrace();
			
		}	
	}
}








jdom读取xml文件:

依赖于jar包: jdom.jar
得到URL的方式Thread.currentThread().getContextClassLoader().getResource(filePath)
package com.wlh.dom4j.test;

import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class TestJdomReader {
	public static void main(String args[]) {
		String filePath = "zxt_index.xml";
		String indexPath="";
		SAXBuilder builder = new SAXBuilder(false);
		try {
			Document doc = builder.build(Thread.currentThread().getContextClassLoader().getResource(filePath));
			Element books = doc.getRootElement();
			 Element rootElement= books.getChild("list");
			 Element index=rootElement.getChild("index");
			 indexPath=index.getText();
			 System.out.println(indexPath);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}



你可能感兴趣的:(thread,xml)