JAVA SE 读写XML——DOM4J

Dom4J

准备工作,先导入jar包

Dom4j.jar下载https://dom4j.github.io/

实例应用

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

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

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

    public void Xmlparse() {
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new File("books.xml"));
            Element bookStore = document.getRootElement();
            bookStore.elementIterator();
            Iterator iterator = bookStore.elementIterator();
            while (iterator.hasNext()) {
                System.out.println("开始遍历一本书");
                Element book = (Element) iterator.next();
                List<Attribute> bookAttrs = book.attributes();
                for (Attribute attr : bookAttrs) {
                    System.out.println("节点名:" + attr.getName() + "  节点值:" + attr.getValue());
                }
                Iterator itt = book.elementIterator();
                while (itt.hasNext()) {
                    Element bookChild = (Element) itt.next();
                    System.out.println("节点名:" + bookChild.getName() + "  节点值" + bookChild.getStringValue());
                }
                System.out.println("结束遍历一本书");
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    public void createXml() {
        Document document = DocumentHelper.createDocument();//创建doc
        Element rss = document.addElement("rss");//添加节点
        rss.addAttribute("version", "2.0");//添加属性值

        Element channel = rss.addElement("channel");//创建子节点
        Element title =channel.addElement("title");//创建子节点
        title.setText("<![CDATA[特殊字符]]>");//设置节点文本
        OutputFormat format = OutputFormat.createPrettyPrint();//设置最优输出设置
        File file = new File("newrss.xml");
        try {
            XMLWriter writer = new XMLWriter(new FileOutputStream(file),format);//创建输出设置器
            writer.setEscapeText(false);//设置是否转义字符
            writer.write(document);//输出文本
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

相关文章——读写xml系列方式

猜你喜欢

转载自blog.csdn.net/weixin_38500325/article/details/81429717