We have introduced how to parse the content of xnl documents before. Here we will discuss how to modify xml.
1. First, take a look at the main code to write the content into the xml document:
XMLWriter writer = new XMLWriter(OutputStream, OutputForamt) wirter.write(Document);
The entire business logic and explanation are as shown in the following code :
##
public class Demo1 { public static void main(String[] args) throws Exception{ //一、读取或创建一个Document对象 //读取day07项目的xm文件(封装数据源) Document doc = new SAXReader().read(new File("./src/contact.xml")); //二、修改Document对象内容.那么这里就把原来的文档给修改了。 //注意:如果这里不做修改数据源文件的内容,则相当于复制功能。 //三、把修改后的Document对象写出到xml文档中 //指定文件输出的位置(封装目的地) FileOutputStream out = new FileOutputStream("d:/contact.xml"); //1.创建写出对象,指定写出位置。 XMLWriter writer = new XMLWriter(out); //2.写出对象,把数据源的文件内容经过修改之后写到目的地文件内去。 writer.write(doc); //3.关闭流 writer.close(); } }
##
public class Demo2 { /** * @param args */ public static void main(String[] args) throws Exception{ Document doc = new SAXReader().read(new File("./src/contact.xml")); //指定文件输出的位置 FileOutputStream out = new FileOutputStream("d:/contact.xml"); /** * 1.指定写出的格式 */ OutputFormat format = OutputFormat.createCompactFormat(); //紧凑的格式.去除空格换行.项目上线的时候使用 //OutputFormat format = OutputFormat.createPrettyPrint(); //漂亮的格式.有空格和换行.开发调试的时候使用 /** * 2.指定生成的xml文档的编码 * 同时影响了xml文档保存时的编码 和 xml文档声明的encoding(xml解析时的编码)的编码。都设置成了一个编码方式保持了一致。 * 结论: 使用该方法生成的xml文档避免中文乱码问题。 */ format.setEncoding("utf-8"); //1.创建写出对象 XMLWriter writer = new XMLWriter(out,format); //2.写出对象 writer.write(doc); //3.关闭流 writer.close(); } }
What we have to do is to modify the "two" part . The next article will explain the entire process in code form, and the process of modifying files with dom4j.
The above is the content introduced by Dom4j to modify the xml document. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!