温馨提示×

java怎么读取xml配置文件

小亿
119
2023-09-11 17:04:42
栏目: 编程语言

在Java中,读取XML配置文件有多种方法,其中比较常用的是使用DOM解析器或者SAX解析器。

  1. 使用DOM解析器:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
// 加载XML配置文件
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("config.xml");
// 获取根节点
Element root = document.getDocumentElement();
// 获取子节点
NodeList nodeList = root.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
// 处理节点数据
String name = element.getAttribute("name");
String value = element.getTextContent();
System.out.println(name + ": " + value);
}
}
  1. 使用SAX解析器:
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
// 创建SAX解析器
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
// 创建处理器
DefaultHandler handler = new DefaultHandler() {
boolean bName = false;
boolean bValue = false;
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("name")) {
bName = true;
}
if (qName.equalsIgnoreCase("value")) {
bValue = true;
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (bName) {
String name = new String(ch, start, length);
System.out.println("Name: " + name);
bName = false;
}
if (bValue) {
String value = new String(ch, start, length);
System.out.println("Value: " + value);
bValue = false;
}
}
};
// 解析XML配置文件
parser.parse("config.xml", handler);

以上是两种常见的读取XML配置文件的方法,你可以根据自己的需求选择适合的方法来读取和处理XML配置文件中的数据。

0