dom4j 读取xml

package core.util;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Reader {
	
	public static String findUrl(String xmlPath,String actionName,String htmlUrlName){
		String remoteUrl = "";
		SAXReader reader = new SAXReader();
		try {
			//读取xml
			Document document = reader.read(new File(xmlPath));
			//获取xml根路径
			Element package_root=document.getRootElement();
			//获root下的所有action子节点
			List<Element> actions = package_root.elements("action");
			for (Element action: actions) {
				//获取action中 属性为name的值 <action name="login"></action> 这里获取的就是login
				if(action.attribute("name").getValue().equals(actionName)){
					//获取name的值等于xx的action下面的子节点
					List<Element> urls = action.elements("remoteHtmlUrl"); 
					for (Element url: urls) {
						if(url.attribute("name").getValue().equals(htmlUrlName)){
							//获取该子节点下面的值<url>http://www.baidu.com</url> 这里获取的是http://www.baidu.com
							remoteUrl = url.getText();
							return remoteUrl;
						}
					}
				}
			}
		} catch (DocumentException e) {
			System.out.println("xml路径不正确,请确认后重试");
			e.printStackTrace();
		}
		return remoteUrl;
	}
}

 

<?xml version="1.0" encoding="UTF-8"?>
<package>
    <action name="login" class="loginController">
        <remoteHtmlUrl name="register">http://www.baidu.com</remoteHtmlUrl>
        <remoteHtmlUrl name="login">http://www.google.com</remoteHtmlUrl>
    </action>
</package>

 

你可能感兴趣的:(dom4j 读取xml)