XML的四种创建方式

前端之家收集整理的这篇文章主要介绍了XML的四种创建方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
话不多说,直接上代码
package com.whoami.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.jdom2.CDATA;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public class XMLCreateRSS {
	public static void main(String[] args) {
		// new DOMCreateXml("bookDomCreate.xml");
		// new SAXCreateXml("bookSAXCreate.xml");
		//new DOM4JCreateXMLRSS("bookDOm4JCreateRSS.xml");
		new JDOMCreateXml("bookJDOMCreateRSS.xml");
	}
}

class DOMCreateXml {
	DOMCreateXml(String path) {

		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.newDocument();
			// 设置xml的样式
			document.setXmlStandalone(true);
			/**
			 * document 文件文件中创建根节点,在根节点中创建子节点
			 */
			// 创建节点
			Element bookstore = document.createElement("bookstore");
			Element book = document.createElement("book");
			Element name = document.createElement("name");
			Element language = document.createElement("language");
			// 添加节点
			// 在文件添加子节点就是根节点
			document.appendChild(bookstore);
			// 在根节点中添加节点,就是根结点的子节点。二级树关系
			bookstore.appendChild(book);
			book.appendChild(name);
			book.appendChild(language);
			// 为book创建属性
			book.setAttribute("id","1");
			// 为name设置值
			name.setTextContent("云计算科学与技术");
			language.setTextContent("English");
			/**
			 * 创建输出TransformerFactory的对象
			 */
			TransformerFactory tff = TransformerFactory.newInstance();

			Transformer tf = tff.newTransformer();
			tf.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
			tf.setOutputProperty(OutputKeys.METHOD,"xml");
			// 设置换行
			tf.setOutputProperty(OutputKeys.INDENT,"yes");
			tf.transform(new DOMSource(document),new StreamResult(new File(path)));
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

/**
 * 使用SAX生成xml文件
 */

class SAXCreateXml {
	SAXCreateXml(String path) {
		// 模拟一个book类型的数据链表
		List<Book> BList = new ArrayList<Book>();
		Book b1 = new Book();
		Book b2 = new Book();
		b1.setId(1);
		b1.setName("三国演义");
		b1.setPrice(99.2);
		b1.setAuthor("罗贯中");
		b1.setTime("1856");
		b2.setId(2);
		b2.setName("西游记");
		b2.setPrice(85.0);
		b2.setAuthor("吴承恩");
		b2.setLanguage("中文");
		b2.setTime("1586");
		BList.add(b1);
		BList.add(b2);
		SAXTransformerFactory stff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
		try {
			TransformerHandler handler = stff.newTransformerHandler();
			Transformer ts = handler.getTransformer();
			ts.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
			ts.setOutputProperty(OutputKeys.METHOD,"xml");
			// 设置换行
			ts.setOutputProperty(OutputKeys.INDENT,"yes");
			// 创建输出文件
			File f = new File(path);
			if (!f.exists()) {

				f.createNewFile();

			}
			// 创建reslut返回值
			Result rs = new StreamResult(f);
			// 利用handler与result关联
			handler.setResult(rs);
			// 利用handler向文件中写入内容
			// 打开domcument
			handler.startDocument();
			AttributesImpl attr = new AttributesImpl();
			handler.startElement("","","BookStore",attr);

			for (Book book : BList) {
				attr.clear();
				attr.addAttribute("","id",String.valueOf(book.getId()));
				handler.startElement("","book",attr);
				if (book.getName() != null && !book.getName().trim().equals("")) {
					attr.clear();
					handler.startElement("","name",attr);
					handler.characters(book.getName().tocharArray(),book.getName().length());
					handler.endElement("","name");
				}
				if (String.valueOf(book.getPrice()) != null && !String.valueOf(book.getPrice()).trim().equals("")) {
					attr.clear();
					handler.startElement("","price",attr);
					handler.characters(String.valueOf(book.getPrice()).tocharArray(),String.valueOf(book.getPrice()).length());
					handler.endElement("","price");
				}
				if (book.getAuthor() != null && !book.getAuthor().trim().equals("")) {
					attr.clear();
					handler.startElement("","author",attr);
					handler.characters(book.getAuthor().tocharArray(),book.getAuthor().length());
					handler.endElement("","author");
				}
				if (book.getTime() != null && !book.getTime().trim().equals("")) {
					attr.clear();
					handler.startElement("","time",attr);
					handler.characters(book.getTime().tocharArray(),book.getTime().length());
					handler.endElement("","time");
				}
				if (book.getLanguage() != null && !book.getLanguage().trim().equals("")) {
					attr.clear();
					handler.startElement("","language",attr);
					handler.characters(book.getLanguage().tocharArray(),book.getLanguage().length());
					handler.endElement("","language");
				}
				// 结束document
				handler.endElement("","book");
			}
			handler.endElement("","BookStore");
			handler.endDocument();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

/**
 * DOM4J创建XML-->RSS
 */
class DOM4JCreateXMLRSS {
	DOM4JCreateXMLRSS(String path) {
		// 创建Element对象
		org.dom4j.Document document = DocumentHelper.createDocument();
		// 创建根节点RSS
		org.dom4j.Element RSS = document.addElement("RSS");
		// 向RSS里面添加属性
		RSS.addAttribute("version","2.0");
		// 生成子节点,和节点内容
		org.dom4j.Element book = RSS.addElement("book");
		org.dom4j.Element title = book.addElement("title");
		title.setText("云计算");
		// 转义符
		org.dom4j.Element name = book.addElement("name");
		name.setText("<!哈哈>");
		// 美化xml样式
		OutputFormat format = OutputFormat.createPrettyPrint();
		// format.setEncoding("GBK");
		// 生成xml文件
		File file = new File(path);
		try {
			XMLWriter write = new XMLWriter(new FileOutputStream(file),format);
			// 设置是否转移,默认为true
			write.setEscapeText(false);
			write.write(document);
			write.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

/**
 * JDOM方式创建xml
 */
class JDOMCreateXml {
	JDOMCreateXml(String path) {
		// 生成一个根结点
		org.jdom2.Element RSS = new org.jdom2.Element("RSS");
		// 添加属性
		RSS.setAttribute("version","2.0");
		// 生成document
		org.jdom2.Document document = new org.jdom2.Document(RSS);
		//创建子节点
		org.jdom2.Element book = new org.jdom2.Element("book");
		RSS.addContent(book);
		book.setAttribute("id","1");
		org.jdom2.Element title = new org.jdom2.Element("title");
		title.setText("语文");
		book.addContent(title);
		org.jdom2.Element language = new org.jdom2.Element("language");
		//language.addContent(new CDATA("<===国内最新新闻==>"));
		language.addContent("<===国内最新新闻==>");
		book.addContent(language);
		Format format = Format.getCompactFormat();
		//设置换行
		format.setIndent("");
		format.setExpandEmptyElements(true);
		//format.setEncoding("GBK");
		XMLOutputter outPuter = new XMLOutputter(format);
		// 利用outPuter将document装换成xml
		File file = new File(path);
		try {
			outPuter.output(document,new FileOutputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

猜你在找的XML相关文章