dom4j读写,用dom4j更改xml文件的数据实际是一个查询更新的过程。
import java.io.File; import java.io.FileWriter; import java.util.Iterator; 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 dom4jTest { public void XMLWriter(){ try { XMLWriter writer = null;// 声明写XML的对象 SAXReader reader = new SAXReader(); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8");// 设置XML文件的编码格式 String filePath = "src/test.xml"; File file = new File(filePath); if (file.exists()) {/**验证文件是否存在*/ Document document = reader.read(file);// 读取XML文件 Element root = document.getRootElement();// 得到根节点 // 添加一个学生信息 Element student = root.addElement("user"); student.addAttribute("id", "001"); Element code = student.addElement("code"); code.setText("100"); Element name = student.addElement("name"); name.setText("张三"); Element sex = student.addElement("sex"); sex.setText("男"); Element age = student.addElement("age"); age.setText("21"); writer = new XMLWriter(new FileWriter(filePath), format); writer.write(document); writer.close(); } else { // 新建student.xml文件并新增内容 Document document = DocumentHelper.createDocument(); Element root = document.addElement("userinfo"); Element student = root.addElement("user"); student.addAttribute("id", "001"); Element code = student.addElement("code"); code.setText("100"); Element name = student.addElement("name"); name.setText("张三"); Element sex = student.addElement("sex"); sex.setText("男"); Element age = student.addElement("age"); age.setText("21"); writer = new XMLWriter(new FileWriter(file), format); writer.write(document); writer.close(); } } catch (Exception e) { e.printStackTrace(); } } public void XMLRead(){ try{ SAXReader reader = new SAXReader(); Document document = reader.read(new File("src/test.xml")); Element root = document.getRootElement(); for (Iterator i = root.elements("user").iterator(); i.hasNext();) { Element user = (Element) i.next(); String code = user.element("code").getText(); String name = user.element("name").getText(); String sex = user.element("sex").getText(); String age = user.element("age").getText();; System.out.print(code+","+name+","+sex+","+age); } }catch(Exception e){ e.printStackTrace(); } } }
xml文件
<?xml version="1.0" encoding="UTF-8"?> <userinfo> <user id="001"> <code>100</code> <name>张三</name> <sex>男</sex> <age>21</age> </user> </userinfo>
时间: 2024-11-09 00:39:17