首页 > 代码库 > Java读取xml配置文件

Java读取xml配置文件

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 = http://www.mamicode.com/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配置文件