You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中遍历指定XML文件并修改节点值?

在Java中使用JDOM遍历并修改XML节点值

我猜你说的org.j相关类库应该是JDOM(毕竟org.jdom是Java处理XML的常用类库),刚好我之前做过类似的需求,给你一套完整的实现方案,涵盖从文件加载、节点遍历修改到保存的全流程:


第一步:引入JDOM依赖

如果你的项目用Maven管理,先在pom.xml中加入JDOM2的依赖:

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

第二步:编写XML处理工具类

下面的工具类包含单个节点替换和批量节点替换两种方法,你可以根据测试用例的需求选择使用:

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class XmlNodeModifier {

    // 单个节点替换方法:接收文件路径、目标节点名、新值
    public void modifySingleXmlNode(String filePath, String targetNodeName, String newValue) throws Exception {
        // 1. 加载XML文件
        SAXBuilder saxBuilder = new SAXBuilder();
        File xmlFile = new File(filePath);
        Document document = saxBuilder.build(xmlFile);

        // 获取根元素和对应的命名空间(必须匹配XML里的ns0)
        Element rootElement = document.getRootElement();
        Namespace ns0 = rootElement.getNamespace();

        // 2. 查找并替换目标节点
        Element targetElement = rootElement.getChild(targetNodeName, ns0);
        if (targetElement != null) {
            targetElement.setText(newValue);
            System.out.println("已替换节点 [" + targetNodeName + "] 的值为: " + newValue);
        } else {
            System.out.println("未找到目标节点: " + targetNodeName);
        }

        // 3. 保存修改后的XML
        saveModifiedXml(document, xmlFile);
    }

    // 批量节点替换方法:支持一次替换多个节点
    public void modifyMultipleXmlNodes(String filePath, NodeReplacement... replacements) throws Exception {
        SAXBuilder saxBuilder = new SAXBuilder();
        File xmlFile = new File(filePath);
        Document document = saxBuilder.build(xmlFile);

        Element rootElement = document.getRootElement();
        Namespace ns0 = rootElement.getNamespace();

        // 遍历所有替换任务
        for (NodeReplacement replacement : replacements) {
            Element targetElement = rootElement.getChild(replacement.nodeName, ns0);
            if (targetElement != null) {
                targetElement.setText(replacement.newValue);
                System.out.println("已替换节点 [" + replacement.nodeName + "] 的值为: " + replacement.newValue);
            } else {
                System.out.println("未找到目标节点: " + replacement.nodeName);
            }
        }

        // 保存修改后的XML
        saveModifiedXml(document, xmlFile);
    }

    // 私有方法:统一处理XML保存逻辑
    private void saveModifiedXml(Document document, File xmlFile) throws IOException {
        XMLOutputter xmlOutput = new XMLOutputter();
        // 设置格式化输出,保持XML的可读性
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(document, new FileWriter(xmlFile));
    }

    // 内部类:封装节点名和新值,用于批量替换
    public static class NodeReplacement {
        String nodeName;
        String newValue;

        public NodeReplacement(String nodeName, String newValue) {
            this.nodeName = nodeName;
            this.newValue = newValue;
        }
    }
}

第三步:测试用例中调用方法

你可以直接从测试用例传入文件路径,调用上面的方法完成修改:

import org.junit.Test;

public class XmlModifierTest {

    @Test
    public void testXmlNodeReplacement() throws Exception {
        XmlNodeModifier modifier = new XmlNodeModifier();
        // 替换成你的XML文件实际路径
        String xmlFilePath = "src/test/resources/studentDetails.xml";

        // 方式1:单个节点替换
        modifier.modifySingleXmlNode(xmlFilePath, "studentName", "Mike");
        modifier.modifySingleXmlNode(xmlFilePath, "studentCGPA", "9.2");

        // 方式2:批量替换多个节点
        modifier.modifyMultipleXmlNodes(xmlFilePath,
                new XmlNodeModifier.NodeReplacement("studentName", "Mike"),
                new XmlNodeModifier.NodeReplacement("studentCode", "9999"),
                new XmlNodeModifier.NodeReplacement("studentCGPA", "9.2")
        );
    }
}

关键注意事项

  • 命名空间处理:你的XML使用了ns0命名空间,所以获取子元素时必须指定对应的Namespace对象,否则会找不到目标节点
  • 文件路径:测试用例中传入的路径要确保正确,若XML是资源文件,注意编译后的路径是否匹配
  • 异常处理:示例中直接抛出了Exception,实际项目建议细化异常捕获(比如IO异常、JDOM解析异常)

内容的提问来源于stack exchange,提问作者80298

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:55:41