XML文件读写工具类
作者:互联网
package com.swft.util;
import java.io.File;
import java.io.FileOutputStream;
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.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* @ClassName: XmlObject
* @description: xml常用工具
* @author: JTJ
* @Date: 2019年2月19日 下午1:02:30
*/
public class XmlObject {
/**
* @Title: readXml
* @Desc: 读取xml内容
* @param xmlFile
* @return xml的字符信息
*/
public String readXml(File xmlFile) {
StringBuilder attribute = new StringBuilder();
StringBuilder element = new StringBuilder();
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(xmlFile);
Element rootElement = document.getRootElement();
@SuppressWarnings("unchecked")
List<Element> elements = rootElement.elements();
for(Element child : elements) {
//属性
@SuppressWarnings("unchecked")
List<Attribute> attributeList = child.attributes();
for (Attribute attr : attributeList) {
attribute.append(attr.getName()+"="+attr.getValue()+"\n");
//System.out.println(attr.getName() + ": " + attr.getValue());
}
@SuppressWarnings("unchecked")
List<Element> elementList = child.elements();
if(elementList.size()!=0) {
for (Element ele : elementList) {
//System.out.println(ele.getName() + ": " + ele.getText());
element.append(ele.getName()+"="+ele.getText()+"\n");
}
}
}
} catch (DocumentException e) {
e.printStackTrace();
}
return attribute.toString()+element.toString();
}
//暂未完成
public Boolean createXml() {
Document doc = DocumentHelper.createDocument();
//增加根节点
Element books = doc.addElement("books");
//增加子元素
Element book1 = books.addElement("book");
Element title1 = book1.addElement("title");
Element author1 = book1.addElement("author");
Element book2 = books.addElement("book");
Element title2 = book2.addElement("title");
Element author2 = book2.addElement("author");
//为子节点添加属性
book1.addAttribute("id", "001");
//为元素添加内容
title1.setText("Harry Potter");
author1.setText("J K. Rowling");
book2.addAttribute("id", "002");
title2.setText("Learning XML");
author2.setText("Erik T. Ray");
//实例化输出格式对象
OutputFormat format = OutputFormat.createPrettyPrint();
//设置输出编码
format.setEncoding("UTF-8");
//创建需要写入的File对象
File file = new File("src" + File.separator + "test" + File.separator + "books.xml");
//生成XMLWriter对象,构造函数中的参数为需要输出的文件流和格式
XMLWriter writer;
try {
writer = new XMLWriter(new FileOutputStream(file), format);
//开始写入,write方法中包含上面创建的Document对象
writer.write(doc);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
标签:XML,文件,dom4j,读写,Element,File,import,org,addElement 来源: https://blog.csdn.net/qq_36984455/article/details/95165474