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

如何用Java文件操作修改XML声明的引号格式?

解决XML声明单引号被替换为双引号的问题

问题分析

你用XML解析工具修改元素文本后,原XML声明的单引号(')被自动改成了双引号("),尝试用字符串替换没成功,核心原因有两个:

  1. replaceAll()方法基于正则表达式匹配,而XML声明里的?和.都是正则特殊字符,直接作为匹配串会导致匹配失败;
  2. 事后字符串替换属于临时hack手段,容易受XML格式细节(比如空格、换行差异)影响,不是最优方案。

方案1:修复字符串替换代码

把replaceAll()换成replace(),后者是普通字符串匹配替换,不会解析正则规则,能直接匹配目标行:

StringBuffer buffer = new StringBuffer();
while (sc.hasNextLine()) {
    buffer.append(sc.nextLine()+System.lineSeparator());
}
String fileContents = buffer.toString();
sc.close();
String oldLine = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
String newLine = "<?xml version='1.0' encoding='UTF-8'?>";
try {
    // 用replace代替replaceAll,避免正则匹配问题
    fileContents = fileContents.replace(oldLine, newLine);
    // 记得将修改后的内容写回原文件
    BufferedWriter writer = new BufferedWriter(new FileWriter("your-file.xml"));
    writer.write(fileContents);
    writer.close();
} catch(Exception e) {
    System.out.println("Not Changed");
    e.printStackTrace();
}

方案2:从XML写入环节控制引号类型(推荐)

更规范的方式是在XML解析工具的输出配置里直接指定用单引号,从根源避免格式变更。以Java DOM解析为例:

写入XML时配置输出属性

// 假设你已经完成Document对象的内容修改
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// 设置XML版本和编码
transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// 关键配置:强制属性值使用单引号(Xalan扩展属性)
transformer.setOutputProperty("{http://xml.apache.org/xalan}quote-attribute-values", "'");
// 保留XML声明
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

// 将修改后的Document写入文件
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("your-output.xml"));
transformer.transform(source, result);

如果使用其他XML库(比如JDOM、DOM4J),也有对应配置项:

  • DOM4J:通过OutputFormat.setQuoteAttributes('\'')设置单引号
  • JDOM:通过XMLOutputter.getFormat().setQuoteAttributes('\'')配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 01:31:01