码迷,mamicode.com
首页 > 编程语言 > 详细

Java读取xml配置文件

时间:2016-12-15 14:50:33      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:des   com   content   cep   getc   ret   分享   extc   ttext   

package test.com;

import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlParser {
public static void main(String[] args) throws Exception {
getXML("src/parameters.xml","HolderName");
}

/**
* @desc 根据key属性的值,获取节点的值
*
*
*/
public static String getXML(String sqlXMLPath, String node) throws Exception {

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
FileInputStream xmlInputStream = new FileInputStream(sqlXMLPath);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(xmlInputStream);

Node n = document.getChildNodes().item(0);
NodeList nl = n.getChildNodes();

for (int i = 0; i < nl.getLength(); i++) {
if (!nl.item(i).getNodeName().equals("#text")) {
Element e = (Element) nl.item(i);
System.out.println(nl.item(i).getNodeName() + "\t" + e.getAttribute("key") + "\t" + nl.item(i).getTextContent());
String key = e.getAttribute("key");
String value = nl.item(i).getTextContent();
if (key.equals(node)) {
return value;
}
}
}
return null;
}

}

 

<?xml version="1.0" encoding="UTF-8"?>

<parameters>
<parameter key="HolderName">测试</parameter>
<parameter key="save-holder">1</parameter>
<parameter key="HolderEmail">ceshi@ceshi.com</parameter>
<parameter key="HolderCardType">3</parameter>
<parameter key="HolderCardNo">asdasd</parameter>
<parameter key="HolderSex">1</parameter>
<parameter key="HolderMobile">13333333333</parameter>
</parameters>

 

技术分享

 

Java读取xml配置文件

标签:des   com   content   cep   getc   ret   分享   extc   ttext   

原文地址:http://www.cnblogs.com/haorun/p/6182867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!