package com.test.xml; import java.io.FileOutputStream; import java.io.IOException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class UpdateXml { public static void main(String[] args) throws JDOMException, IOException { // 以下三行为读取xml->doc的固定步骤。得到根元素 SAXBuilder sb = new SAXBuilder(); Document doc = sb.build("d:/2.xml"); Element root = doc.getRootElement(); Element e = root.getChild("appSettings"); System.out.println(e.getText()); Element e2 = root.getChild("limit"); System.out.println(e2.getText()); e2.setText("150"); //以下4行为固定写入xml的格式,套用就行,将doc写回xml Format f = Format.getPrettyFormat(); // 相当于<?xml version="1.0" encoding="gbk"?> f.setEncoding("gbk"); // 写进硬盘,这个套用就行。路径左斜杠,一个,右斜杠2个 XMLOutputter xmlout = new XMLOutputter(f); xmlout.output(doc, new FileOutputStream("d:\\2.xml")); } }
时间: 2024-12-11 06:32:47