一、maven依赖
1 2 3 4
| <dependency> <groupId>org.apache.servicemix.bundles</groupId> <artifactId>org.apache.servicemix.bundles.dom4j</artifactId> <version>1.6.1_5</version> </dependency>
|
二、概述
java中解析xml有两种方式:
DOM解析:
将整个xml文档解析成Document对象放在内存中。
增,删,改,查都很方便,但是非常占用内存,一般用在服务器系统中。
SAX解析:
流式解析,存在一个指针,指针永远指向一行,每次指针向下移动,通过回调函数操作。
占用内存小,但是只能做查询,一般用在小内存机器,如手机中。
java内置的xml解析方式:
jaxp 方式。
这里使用的是第三方工具:Dom4j
核心类
SAXReader
1 2
| SAXReader saxReader = new SAXReader();
|
DocumentHelper
1 2 3
| DocumentHelper DocumentHelper.parseText("xml 字符串");
|
Document
Element
1
| element 对象,存在于 document 对象中
|
XMLWriter
1 2
| XMLWriter xmlWriter = new XMLWriter();
|
三、操作
获取 Document 对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| @Test public void getDocByXMLFile() throws DocumentException { Document document = saxReader.read(FileUtil.getUrl("example.xml")); LOG.info("通过XML文件取得 Document 对象:" + document); }
@Test public void getDocByXMLStr() throws DocumentException { Document document = DocumentHelper.parseText("<note>\n" + " <to>George</to>\n" + " <from>John</from>\n" + " <heading>Reminder</heading>\n" + " <body>Don't forget the meeting!</body>\n" + "</note>"); LOG.info("通过 DocumentHelper 解析文本创建 Document 对象:" + document); }
@Test public void getDocByCreate() { Document document = DocumentHelper.createDocument(); LOG.info("通过 DocumentHelper 直接创建 Document 对象:" + document); }
|
获取节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Test public void getNode(){ Element rootElm = document.getRootElement(); Element fromElm = rootElm.element("from"); String fromElmText = fromElm.getText(); LOG.info("from节点的文本: " + fromElmText); List<Element> headingElms = rootElm.elements("heading"); LOG.info("root 下面 所有 heading 节点:"); headingElms.forEach(val -> LOG.info(val.getText())); List<Element> elements = rootElm.elements(); LOG.info("root 下面 所有节点:"); elements.forEach(val -> LOG.info(val.getText())); }
|
增加节点
1 2 3 4 5 6 7 8 9
| @Test public void addNode() throws IOException { Element rootElm = document.getRootElement(); Element extrasElm = rootElm.addElement("extras"); extrasElm.setText("额外"); XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File("result.xml"))); xmlWriter.write(document); }
|
删除节点
1 2 3 4 5 6 7 8 9 10
| @Test public void removeNode() throws IOException { Element rootElm = document.getRootElement(); Element extrasElm = rootElm.element("heading"); Assert.assertNotNull(extrasElm); rootElm.remove(extrasElm); XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(new File("result.xml"))); xmlWriter.write(document); }
|