xml程序 个人练习1

package cn.gdpe.xml2;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlWriter {
public static void main(String[] args){
new XmlWriter().modify();
}

private void create() {
try {
//读取文档
// Document dc=new SAXReader().read("src/xml1.xml");
String path=new File("src").getAbsolutePath();
//创建文档
Document dc=DocumentHelper.createDocument();
//修改文档
//写到文件中
//指定写出的格式
OutputFormat format=OutputFormat.createCompactFormat();//紧凑的格式 去除空格换行
OutputFormat format2=OutputFormat.createPrettyPrint();//漂亮的格式 不去除空格换行
File file=new File(path+"/xml2.xml");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream fos=new FileOutputStream(file);
XMLWriter writer=new XMLWriter(fos,format);
XMLWriter writer2=new XMLWriter(fos,format2);
writer.write(dc);
writer.close();
fos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public void modify(){
try {
Document dc=new SAXReader().read("src/xml2.xml");
List<Element> els=dc.getRootElement().elements("person");
//增加元素
// Element addE=els.get(0).addElement("age");
// addE.addText("25");

//修改文本 1
// els.get(0).element("name").setText("ly");

//修改属性 2
// els.get(0).attribute("id").setValue("009");

//删除元素
Element e=els.get(0).element("age");
e.getParent().remove(e);

//指定写出的格式
String path=new File("src").getAbsolutePath();
// OutputFormat format=OutputFormat.createCompactFormat();//紧凑的格式 去除空格换行
OutputFormat format2=OutputFormat.createPrettyPrint();//漂亮的格式 不去除空格换行
File file=new File("src/xml2.xml");
FileOutputStream fos=new FileOutputStream(file);
// XMLWriter writer=new XMLWriter(fos,format);
XMLWriter writer2=new XMLWriter(fos,format2);
writer2.write(dc);
writer2.close();
fos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

原文地址:https://www.cnblogs.com/ly-china/p/5418190.html