jdom读取xml
程序员文章站
2022-05-28 10:51:53
...
config.xml文档
<?xml version="1.0" encoding="UTF-8"?> <configure> <driver-class-name>oracle.jdbc.driver.OracleDriver</driver-class-name> <url>jdbc:oracle:thin:@127.0.0.1:1521:ora9i</url> <username>xsfw</username> <password>xsfw</password> </configure>
读取xml文档,利用xpath,可见学习好xpath对于操作xml是多么的重要啊!
package test.jdom;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class readXML {
public static void main(String[] args) {
SAXBuilder sb=new SAXBuilder();
try {
Document doc=sb.build("config.xml");
Element root=doc.getRootElement();
Element driverNameElt=(Element)XPath.selectSingleNode(root,"//configure/driver-class-name");
String driver=driverNameElt.getText();
Element urlElt=(Element)XPath.selectSingleNode(root,"//configure/url");
String url=urlElt.getText();
Element userNameElt=(Element)XPath.selectSingleNode(root,"//configure/username");
String username=userNameElt.getText();
Element passwordElt=(Element)XPath.selectSingleNode(root,"//configure/password");
String pwd=passwordElt.getText();
System.out.println(driver);
System.out.println(url);
System.out.println(username);
System.out.println(pwd);
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
上一篇: Java JDom 解析xml