JavaEE XML的读写(利用JDom对XML文件进行读写)
生活随笔
收集整理的這篇文章主要介紹了
JavaEE XML的读写(利用JDom对XML文件进行读写)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.有關(guān)XML的寫
利用JDom2包,JDom2這個(gè)包中,至少引入org.jdom2.*;如果要進(jìn)行XML文件的寫出,則要進(jìn)行導(dǎo)入org.jdom2.output.*;
package com.littlepage.test1;import java.io.*; import org.jdom2.*; import org.jdom2.output.*;public class Test3 {public static void main(String[] args) {try {Element rootElement = new Element("rootElement");Document document = new Document(rootElement);rootElement.addContent(new Element("student1").addContent(new Element("name").addContent("Jack")).setAttribute("type","transfer student"));rootElement.addContent(new Element("student1").addContent(new Element("name").addContent("Nancy")));rootElement.addContent(new Element("student1").addContent(new Element("name").addContent("Lucy")));XMLOutputter xop = new XMLOutputter();//設(shè)置間距XMLOutputter out=new XMLOutputter();Format format=out.getFormat();format.setEncoding("GB2312");format.setIndent("\n\t");out.setFormat(format);xop.output(document, new FileWriter("student.xml"));} catch (IOException e) {e.printStackTrace();}} }?
XML文件寫入結(jié)果
<?xml version="1.0" encoding="UTF-8"?> <rootElement><student1 type="transfer student"><name>Jack</name></student1><student1><name>Nancy</name></student1><student1><name>Lucy</name></student1> </rootElement>?
?
2.有關(guān)XML文件的讀
利用SAXBuilder,SAXBuilder在org.xml.input.*;中存在方法SAXBuilder,SAXBuilder是進(jìn)行XML文件讀入的一個(gè)類
?
//遞歸打印XML的document public class Test4 {public static void main(String[] args) {try{Document document=new SAXBuilder().build("MyXML.xml");Element rootElement=document.getRootElement();recursionXML(rootElement);}catch(IOException|JDOMException e){e.printStackTrace();}}/*** recursion XML,for print the root element* @param element*/public static void recursionXML(Element element){System.out.println(element.getName()+":"+element.getText());if(!element.getChildren().isEmpty()){List<Element> li=element.getChildren();for (Element element2 : li) {recursionXML(element2);}}}/ }轉(zhuǎn)載于:https://www.cnblogs.com/littlepage/p/10492388.html
總結(jié)
以上是生活随笔為你收集整理的JavaEE XML的读写(利用JDom对XML文件进行读写)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Git 分支 - 分支的新建与合并
- 下一篇: 盒模型的实际尺寸