在Java应用里,XML和Properties是两种常见的配置载体。XML善于描述树形结构,Properties则以简单的key=value方便程序加载。实际工作中常常要把已有的XML配置导出成Properties,或者把Properties转成XML便于其他系统读取。借助Java自带的类库,我们可以写出轻量工具完成互转。

一、XML转Properties
思路是读取XML文档,递归遍历每个节点,用点号拼接父节点名与当前节点名作为key,把叶子节点的文本作为value。下面给出一个简单实现:
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import java.util.Properties;
public class XmlToProperties {
public static void main(String[] args) throws Exception {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new File("config.xml"));
Properties props = new Properties();
// 从根节点开始递归
parseElement(doc.getDocumentElement(), "", props);
props.store(new FileOutputStream("config.properties"), "converted");
}
private static void parseElement(Element el, String prefix, Properties props) {
NodeList children = el.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element child = (Element) node;
String key = prefix.isEmpty() ? child.getTagName() : prefix + "." + child.getTagName();
// 若还有子元素则继续递归
if (child.getChildNodes().getLength() == 1 && child.getFirstChild().getNodeType() == Node.TEXT_NODE) {
props.setProperty(key, child.getTextContent().trim());
} else {
parseElement(child, key, props);
}
}
}
}
}
二、Properties转XML
Java的Properties类本身提供了storeToXML方法,可以直接把键值对写成XML格式,无需自己拼标签:
import java.io.*;
import java.util.Properties;
public class PropertiesToXml {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.load(new FileInputStream("config.properties"));
// 直接调用标准库方法输出XML
props.storeToXML(new FileOutputStream("config_out.xml"), "generated", "UTF-8");
}
}
三、注意事项
- XML里如果同一层级有重复标签名,转成Properties会出现key覆盖,需要业务上避免或改用列表标记。
- Properties的key不支持真正的树结构,深层嵌套建议用点号分隔保持可读性。
- 读取外部文件时注意指定字符集,防止中文乱码。
四、小结
使用Java标准API就能完成XML与Properties互转,小型项目不必引入额外依赖。若配置复杂,可考虑Apache Commons Configuration等库。理解节点与键值映射规则,自己写的工具也更贴合团队规范。
XMLPropertiesJavaformat_conversionconfig_file修改时间:2026-07-25 00:48:17