本文主要是介绍用SAXReader解析xml文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
x5config.xml里面的xml内容
<?xml version="1.0" encoding="utf-8"?>
<x5-config>
<business-server>http://127.0.0.1:8080/BusinessServer</business-server>
<login-name>system</login-name>
<password>123456</password>
</x5-config>
java 代码
public String login() throws DocumentException, UnknownHostException {
// 从配置文件读取服务器地址和分配给第三方接口的用户
SAXReader reader = new SAXReader();
Document dom = reader.read(getClass().getResource("/").getPath() + "/../x5config.xml");
String businessServer = dom.selectSingleNode("/x5-config/business-server").getText();
String loginName = dom.selectSingleNode("/x5-config/login-name").getText();
String password = dom.selectSingleNode("/x5-config/password").getText();
// 获得本地IP地址
String localIP = java.net.InetAddress.getLocalHost().getHostAddress();
// 初始化动作引擎
ActionEngine.init(businessServer);
// 登录
String bSessionID = ActionEngine.login(loginName, ActionUtils.md5(password), localIP, null);
// 返回bSessionID
return bSessionID;
}
=======================案例2===================================
使用SAXReader需要导入dom4j-full.jar包。
dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的。dom4j是一个非常非常优秀的Java XML API,具有性能优异、功能强大和极端易用使用的特点,同时它也是一个开放源代码的软件,可以在SourceForge上找到它。
使用举例:
1. s.xml内容
- <?xml version="1.0" encoding="GB2312"?>
- <data>
- <row queryDTO.enterpriseId="gfd" queryDTO.loginName="gdfg" queryDTO.state="0"/>
- </data>
2.解析
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.util.Iterator;
- import java.util.List;
- import org.dom4j.Document;
- import org.dom4j.DocumentException;
- import org.dom4j.Element;
- import org.dom4j.io.SAXReader;
- import org.dom4j.tree.AbstractAttribute;
-
- public class ReadXMLTest {
-
- public static void main(String[] args){
- File xmlFile = new File("C:/s.xml");
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(xmlFile);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- System.err.println("File is not exsit!");
- }
-
- SAXReader saxReader = new SAXReader();
- List rowList = null;
- try {
-
- Document doc = saxReader.read(fis);
-
- rowList = doc.selectNodes("//data/row");
- } catch (DocumentException e) {
- e.printStackTrace();
- }
-
-
- for(Iterator iter = rowList.iterator();iter.hasNext();){
-
- Element element = (Element)iter.next();
-
- List elementList = element.attributes();
- for(Iterator iter1 = elementList.iterator();iter1.hasNext();){
-
- AbstractAttribute aa = (AbstractAttribute)iter1.next();
- System.out.println("Name:"+aa.getName()+";Value:"+aa.getValue());
- }
-
-
-
-
- System.out.println(element.getName());
-
-
-
- System.out.println(element.attributeValue("queryDTO.enterpriseId"));
-
-
-
- System.out.println(element.elementText("width"));
- }
-
- }
- }
这篇关于用SAXReader解析xml文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!