dom4j创建XML添加属性和标签和内容添加CDATA 删除属性

来源:互联网 发布:淘宝旺旺名称怎么修改 编辑:程序博客网 时间:2024/06/05 11:16
package com.lanou.day19.test;import java.io.FileWriter;import java.io.IOException;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import org.dom4j.Attribute;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import com.lanou.day17.entity.Person;import com.lanouday12.DVD;import com.lanouday12.DVDAdmin;public class TestArr3 {public static void main(String[] args) {        String path=System.getProperty("user.dir")+"/src/com/lanou/day19/test/lala.xml";        Document document=DocumentHelper.createDocument();        Element root=document.addElement("students");        root.addAttribute("teacher", "lck");        root.addAttribute("teacher1","meimei" );        root.remove(root.attribute("teacher1"));        Element student=root.addElement("student");        student.addAttribute("name","xwj");        Element lala=student.addElement("lala");        lala.addCDATA("lalalllla");                SAXReader reader=new SAXReader();        try {Document document2=reader.read(path);Element root2=document2.getRootElement();for(Iterator<Attribute> iterator=root2.attributes().iterator();iterator.hasNext();) {Attribute attribute=iterator.next();System.out.println(attribute.getName());System.out.println(attribute.getText());}} catch (DocumentException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}                            try {          XMLWriter xmlWriter=new XMLWriter(new FileWriter(path));xmlWriter.write(document);xmlWriter.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}               }}