java 中通过 javax.xml.parsers.documentbuilder 解析 xml 配置文件,利用 java.io.filereader 或 java.nio.file.files 读取文件流,再结合 org.w3c.dom.document 获取节点数据。具体做法是构建工厂实例,调用 parse() 方法将文件转为 dom 树,随后遍历节点提取配置项并写入 java 对象。若遇到空文件或格式错误,解析器会抛出异常,需提前捕获处理。

如何解析 XML 中的根节点属性
使用 DocumentBuilderFactory 创建解析器后,调用 getDocumentElement() 可直接获取根节点。通过
getAttribute()</code 方法传入属性名即可读取值。此操作不涉及子节点,仅针对顶层标签的键值对进行提取。</p><p><img src="https://img.php.cn/upload/article/001/242/473/179505800918736.png" alt="Java 文件读写怎么用 XML 解析读写配置"></p>
<pre class="brush:php;toolbar:false;">import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;
public class XmlConfigReader {
public static void main(String[] args) throws Exception {
File file = new File("config.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
Element root = doc.getDocumentElement();
String version = root.getAttribute("version");
System.out.println("Root Version: " + version);
}
}
如何遍历 XML 中的子节点列表
在获取到父节点后,调用 getChildNodes() 返回 <code>NodeList。遍历该列表时,需检查节点类型是否为 ELEMENT_NODE,再通过 getNodeName() 和 getTextContent() 获取标签名与内容。这种方式适用于读取重复结构的配置项,如多个数据库连接池设置。
立即学习“Java免费学习笔记(深入)”;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class NodeListWalker {
public static void walk(Node parent) {
NodeList children = parent.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(child.getNodeName() + ": " + child.getTextContent());
}
}
}
}
当 XML 节点内容为空字符串时如何处理
如果 XML 标签内没有文本内容,getTextContent() 会返回空字符串而非 null。此时直接使用该值可能导致业务逻辑误判。应在读取后立即判断长度,若为空则赋予默认值或跳过该配置项。这种情形常见于可选配置字段未填写的情况。


















