JAVA生成XML
Posted 故意的是吧
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA生成XML相关的知识,希望对你有一定的参考价值。
DOM方式:
package DomTest;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DOMTest
/***
* 生成XML
*/
public void creatXML()
DocumentBuilder db=getDocumentBuilder();
Document document=db.newDocument();
document.setXmlStandalone(true);//设置XML的standalone属性
//创建根节点
Element bookstore= document.createElement("bookStore");
//添加子节点book
Element book=document.createElement("book");
//添加子节点name
Element name=document.createElement("name");
book.appendChild(name);
//添加子节点内容
name.setTextContent("人猿泰山");
book.setAttribute("id", "1");
//将book子节点添加到bookstore中
bookstore.appendChild(book);
//将bookstore节点(已包含book)添加到dom数中
document.appendChild(bookstore);
//
TransformerFactory tff=TransformerFactory.newInstance();
try
Transformer tf=tff.newTransformer();
//让DOM树输出过程中正常换行
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(document), new StreamResult(new File("books1.xml")));
catch (TransformerException e)
// TODO Auto-generated catch block
e.printStackTrace();
public static DocumentBuilder getDocumentBuilder()
// 创建一个DocumentBuilderFactory对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 创建DocumentBuilder对象
DocumentBuilder db=null;
try
db = dbf.newDocumentBuilder();
catch (ParserConfigurationException e)
// TODO Auto-generated catch block
e.printStackTrace();
return db;
public static void main(String[] args)
// 创建一个DocumentBuilder的对象
try
// 通过DocumentBuilder对象的parse方法加载books.xml文件
// 到当前项目下
Document document = getDocumentBuilder().parse("books.xml");
// 获取所有book节点的集合
NodeList bookList = document.getElementsByTagName("book");
//通过nodeList的getLength()方法获取bookLIst的长度
System.out.println("一共有:"+bookList.getLength()+"本书");
//便利各个book节点
for (int i = 0; i < bookList.getLength(); i++)
System.out.println("++++++++++++开始遍历第"+(i+1)+"本书+++++++++++");
//方式一,不知道有多少节点,通过循环来遍历所有节点。
//通过 item(i)获取一个book节点,nodeList
Node book=bookList.item(i);
//获取book的属性的集合
NamedNodeMap attrs=book.getAttributes();
System.out.println("第"+(i+1)+"本书共有"+attrs.getLength()+"个属性");
//便利book的属性
for (int j = 0; j < attrs.getLength(); j++)
//通过item()方法获取book节点的某一个属性
Node attr=attrs.item(j);
//获取属性名
System.out.println("属性名:"+attr.getNodeName());
//获取属性值
System.out.println("属性值:"+attr.getNodeValue());
// //方式二,知道有且只有一个节点。并且知道属性的名称为“id”
// //强制类型转换将book节点类型转换为Element类型
// Element book =(Element) bookList.item(i);
//
// //通过getAttribute(“id”)方法获取到属性的值
// String attrValue=book.getAttribute("id");
// System.out.println("id的属性的属性值为"+attrValue);
//解析book节点的子节点,需要用到方式一中创建的book对象
//获取子节点的集合
NodeList childNodes=book.getChildNodes();
//遍历childNodes获取每个子节点的节点名和节点值
System.out.println("第"+(i+1)+"本书共有"+childNodes.getLength()+"个子节点");
//循环遍历
for (int j = 0; j < childNodes.getLength(); j++)
//区分text类型的node和element类型的node
if(childNodes.item(j).getNodeType()==Node.ELEMENT_NODE)
//输出了element类型节点的节点名
System.out.println("第"+(j+1)+"个节点名:"+childNodes.item(j).getNodeName());
//输出element类型节点的节点值
//需先获取当前节点的首个子节点,否则获取的是《name》标签的值NULL
//方式一:如果<name>节点下有多个子节点,此方法只输出确定的某个子节点的值
//同样要注意,<name>节点的第一个子节点的值是第一子节点的类型的值,还是NULL
System.out.println("节点值为:"+childNodes.item(j).getFirstChild()
.getNodeValue());
//方式二:如果<name>节点下有多个子节点,此方法输出所有子节点的text
System.out.println(childNodes.item(j).getTextContent());
System.out.println("++++++++++++结束遍历第"+(i+1)+"本书++++++++++++");
catch (SAXException e)
e.printStackTrace();
catch (IOException e)
e.printStackTrace();
DOMTest test=new DOMTest();
test.creatXML();
SAX方式:
使用SAX解析时创建的SAXParserHandler.java
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import test2.SAXParserHandler;
import test3.Book;
public class SAXTest
public ArrayList<Book> parseXML()
// 通过SAXParseFactory的静态newInstance()
//方法获取SAXParseFactory实例factory
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParserHandler handler=null;
//通过SAXParserFactory实例的newSAXParser()
//方法返回SAXParse实例parser
try
SAXParser parser= factory.newSAXParser();
//创建SAXParserHandler对象
handler=new SAXParserHandler();
parser.parse("books.xml", handler);
System.out.println("书的数量:"+handler.getBookList().size());
for(Book book: handler.getBookList())
System.out.println(book.getId());
System.out.println(book.getName());
System.out.println(book.getAuthor());
System.out.println(book.getPrice());
System.out.println(book.getYear());
System.out.println("-------------");
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (ParserConfigurationException | SAXException e)
// TODO Auto-generated catch block
e.printStackTrace();
return handler.getBookList();
public void createXML()
ArrayList<Book> bookList=parseXML();
//生成XML
//1、创建一个TransformFacroty对象
SAXTransformerFactory tff=(SAXTransformerFactory)
SAXTransformerFactory.newInstance();
try
//2、通过SAXTransformerFactory对象创建一个TransformerHandler对象
TransformerHandler handler=tff.newTransformerHandler();
//3、通过handler对象创建一个Transformer对象
Transformer tr=handler.getTransformer();
//4、通过Transformer对象对生成的XML文件进行设置
//设置XML编码
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//设置换行
tr.setOutputProperty(OutputKeys.INDENT, "yes");
//5、创建一个Result对象
File f=new File("src/newbooks.xml");
if(!f.exists())
f.createNewFile();
Result result=new StreamResult(new FileOutputStream(f));
//6、创建result对象并使其与handler关联
handler.setResult(result);
//7、使用handler对象进行XML文件的编写
//打开document
handler.startDocument();
AttributesImpl attr=new AttributesImpl();
//开始标签
handler.startElement("", "", "bookstore", attr);
for(Book book:bookList)
attr.clear();
attr.addAttribute("", "", "id", "", book.getId());
handler.startElement("", "", "book", attr);
attr.clear();
//创建name节点
handler.startElement("", "", "name", attr);
handler.characters(book.getName().toCharArray(),
0, book.getName().length());
handler.endElement("", "", "name");
//创建author节点
attr.clear();
handler.startElement("", "", "author", attr);
handler.characters(book.getAuthor().toCharArray(),
0, book.getAuthor().length());
handler.endElement("", "", "author");
//创建price节点
attr.clear();
handler.startElement("", "", "price", attr);
handler.characters(book.getPrice().toCharArray(),
0, book.getPrice().length());
handler.endElement("", "", "price");
//创建year节点
//判断当有此节点时才进行创建操作
if(book.getYear()!=null&&!book.getYear().trim().equals(""))
attr.clear();
handler.startElement("", "", "year", attr);
handler.characters(book.getYear().toCharArray(),
0, book.getYear().length());
handler.endElement("", "", "year");
handler.endElement("", "", "book");
//结束标签
handler.endElement("", "", "bookstore");
//关闭document
handler.endDocument();
catch (TransformerConfigurationException | IOException | SAXException e)
// TODO Auto-generated catch block
e.printStackTrace();
public static void main(String[] args)
SAXTest test=new SAXTest();
test.createXML();
DOM4J方式:
RSS就是一个特殊格式的XML
package Dom4jTest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
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;
public class DOM4JTest
public static void main(String[] args)
new DOM4JTest().createXML();
public void parseXML()
// TODO Auto-generated method stub
// 创建SAXReader对象
SAXReader reader = new SAXReader();
// 通过reader对象read 方法加载book.xml
try
Document document = reader.read(new File("src/res/books.xml"));
// 通过document对象获取根节点bookstore
Element bookStore = document.getRootElement();
// 通过element对象的elementIterator方法获取迭代器
Iterator it = bookStore.elementIterator();
// 遍历迭代器,获取根节点中的信息
while (it.hasNext())
System.out.println("开始遍历一本书");
Element book = (Element) it.next();
// 获取book的属性名和属性值
List<Attribute> bookAttrs = book.attributes();
for (Attribute attr : bookAttrs)
System.out.println("属性名:" + attr.getName() + "\\t属性值:" + attr.getValue());
Iterator itt = book.elementIterator();
while (itt.hasNext())
Element bookChild = (Element) itt.next();
System.out.println("节点名:" + bookChild.getName() + "\\t节点值:" + bookChild.getStringValue());
System.out.println("结束遍历一本书" + "\\n");
catch (DocumentException e)
// TODO Auto-generated catch block
e.printStackTrace();
public void createXML()
//1、创建Document对象,代表整个XML
Document document=DocumentHelper.createDocument();
//2、创建根节点
Element rss=document.addElement("rss");
//3、向rss节点中添加version属性
rss.addAttribute("version", "2.0");
//4、生成子节点及内容
Element channel=rss.addElement("channel");
Element title=channel.addElement("title");
title.setText("新闻资讯");
//设置换行
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
//5、生成XML文件
File file=new File("rssnews.xml");
XMLWriter writer;
try
writer = new XMLWriter(new FileOutputStream(file),format);
//设置是否转义,默认是true进行转义
writer.setEscapeText(false);
writer.write(document);
writer.close();
catch (UnsupportedEncodingException e1)
// TODO Auto-generated catch block
e1.printStackTrace();
catch (FileNotFoundException e1)
// TODO Auto-generated catch block
e1.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
JDOM方式:
package test;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import test3.Book;
public class JDOMTest
private static ArrayList<Book> booksList = new ArrayList<Book>();
public static void main(String[] args)
new JDOMTest().createXML();
public void parserXML()
// JDOM解析XML文件
// 创建一个SAXBuilder对象
SAXBuilder saxbuilder = new SAXBuilder();
InputStream in;
try
// 创建一个输入流,将xml文件加载到流中
in = new FileInputStream("src/res/books.xml");
// InputStreamReader ins=new InputStreamReader(in,"UTF-8");
// 通过saxbuilder的build方法将输入流加载到saxbuilder中
Document document = saxbuilder.build(in);
// 通过document对象获取xml文件的根节点
Element rootElement = document.getRootElement();
// 获取根节点下的子节点的集合
List<Element> bookList = rootElement.getChildren();
// 使用foreach循环解析
for (Element book : bookList)
Book bookEntity = new Book();
System.out.println("开始解析第" + (bookList.indexOf(book) + 1) + "本书============");
// 解析book的属性
List<Attribute> attrList = book.getAttributes();
// //知道节点属性名
// book.getAttribute("id");
// 针对不清楚book节点下属性名和数量的情况
// 遍历attrList
for (Attribute attr : attrList)
// 获取属性名和属性值
String attrName = attr.getName();
String attrValue = attr.getValue();
System.out.println("属性名:" + attrName + "\\t属性值:" + attrValue);
// 存储book节点
if (attrName.equals("id"))
bookEntity.setId(attrValue);
// 对book节点的子节点的节点名和节点值进行遍历
List<Element> bookChilds = book.getChildren();
for (Element child : bookChilds)
System.out.println("节点名:" + child.getName() + "\\t节点值:" + child.getValue());
// 存储子节点名
if (child.getName().equals("name"))
bookEntity.setName(child.getValue());
else if (child.getName().equals("author"))
bookEntity.setAuthor(child.getValue());
else if (child.getName().equals("year"))
bookEntity.setYear(child.getValue());
else if (child.getName().equals("price"))
bookEntity.setPrice(child.getValue());
System.out.println("结束解析第" + (bookList.indexOf(book) + 1) + "本书============");
// 添加booksList集合对象
booksList.add(bookEntity);
bookEntity = null;
System.out.println(booksList.size());
System.out.println(booksList.get(0).getId());
System.out.println(booksList.get(0).getName());
catch (FileNotFoundException e1)
// TODO Auto-generated catch block
e1.printStackTrace();
catch (JDOMException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
public void createXML()
//1、生成一个根节点
Element rss=new Element("rss");
rss.setAttribute("version","2.0");//添加节点属性
//2、生成一个document对象
Document document=new Document(rss);
Element channel=new Element("channel");
rss.addContent(channel);
Element title=new Element("title");
title.setText("ceshiceshi测试");
channel.addContent(title);
Format format=Format.getCompactFormat();
format.setIndent("");
format.setEncoding("GBK");
//创建XMLOutputter对象
XMLOutputter outputer=new XMLOutputter(format);
try
outputer.output(document, new FileOutputStream(new File("rssnews")));
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
生成方式对比
DOM 基于树结构,始终在内存中,方便增删改操作
SAX基于事件
JDOM 基于底层API
DOM4J基于底层API
以上是关于JAVA生成XML的主要内容,如果未能解决你的问题,请参考以下文章