- 下载dom4j.jar对应的版本并导入到项目中
- xml格式数据模型:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book bookno="1">
<title>book01</title>
<author>fsr</author>
<price>20.0</price>
</book>
<book bookno="2">
<title>book11</title>
<author>fsr</author>
<price>30.0</price>
</book>
<book bookno="3">
<title>book21</title>
<author>fsr</author>
<price>40.0</price>
</book>
</books>
- 拼装xml格式数据字符串并以xml类型文件保存到磁盘中
package xml_dom;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import xml_sax.Book;
/*
功能:根据对象集合拼装xml格式字符串,然后输出为xml文件保存到磁盘
String 最大长度65536个字节,除去null占用了2个字节,剩65534个字节,如果字符串中存在中文(一个中文占3个字节:UTF-8),那么字符数量将更少
*/
public class XmlStringToXmlFile {
static Document builderXmlStr(List<Book> bList) throws Exception
{//根据对象集合来创建XML格式的字符串,并构建为Document对象返回
//StringBuffer strbuf=new StringBuffer();
StringBuilder xmlStr=new StringBuilder();
if(bList!=null&&bList.size()>0)
{
xmlStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
xmlStr.append("<books>");
for(int i=0;i<bList.size();i++)
{//根据书的集合对象,循环拼装书这个节点
Book b=bList.get(i);
xmlStr.append("<book bookno=\"").append(b.getBookNo()).append("\">");
xmlStr.append("<title>").append(b.getTitle()).append("</title>");
xmlStr.append("<author>").append(b.getAuthor()).append("</author>");
xmlStr.append("<price>").append(b.getPrice()).append("</price>");
xmlStr.append("</book>");
}
xmlStr.append("</books>");
}
Document doc=DocumentHelper.parseText(xmlStr.toString());
return doc;
}
public static void outputXmlFile(Document doc,String filename)
{//将Document对象对应的xml格式数据输出到xml文件中保存起来
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer;
try {
writer=new XMLWriter(new FileWriter(new File(filename)),format);
writer.write(doc);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
List<Book> bookList=new ArrayList<Book>();
for(int i=0;i<5;i++)
{
bookList.add(new Book(String.valueOf(i+1),"book"+i+1,"fsr",i*10+20));
}
Document doc=builderXmlStr(bookList);
long time=Calendar.getInstance().getTimeInMillis();//当前时间戳
String filename="e:\\"+String.valueOf(time)+".xml";
outputXmlFile(doc,filename);
}
}
4、读取xml格式文件并解析各节点的数据
package xml_dom;
import java.io.File;
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 org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import xml_sax.Book;
import xml_sax.XmlParse;
public class DomXmlParser implements XmlParse {
@Override
public List<Book> parseXml(String fileName) {
// TODO Auto-generated method stub
List<Book> list=new ArrayList<Book>();
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
Document doc=null;
try {
DocumentBuilder builder=factory.newDocumentBuilder();
doc=builder.parse(new File(fileName));
} catch (ParserConfigurationException e) {e.printStackTrace();
} catch (SAXException e) { e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
}
//获得根元素<books>
Node rootNode=doc.getDocumentElement();
//获取<book>元素列表
NodeList bookElementList=rootNode.getChildNodes();
for(int i=0;i<bookElementList.getLength();i++)
{
Node bookElement=bookElementList.item(i);
if(bookElement.getNodeName().equals("book"))
{
//获取<book>元素属性列表,从其中获取bookno属性
Book book =new Book();
NamedNodeMap map=bookElement.getAttributes();
Node booknoNode=map.getNamedItem("bookno");
book.setBookNo(booknoNode.getNodeValue());
//获取子节点列表,循环获取子节点数据
NodeList subBookElementList=bookElement.getChildNodes();
for(int j=0;j<subBookElementList.getLength();j++)
{
Node subElementNode=subBookElementList.item(j);
String nodeName=subElementNode.getNodeName();
if(nodeName.equals("title"))
{
book.setTitle(subElementNode.getTextContent().trim());
}
else if(nodeName.equals("author"))
{
book.setAuthor(subElementNode.getTextContent().trim());
}
else if(nodeName.equals("price"))
{
book.setPrice(Double.parseDouble(subElementNode.getTextContent().trim()));
}
}
list.add(book);
}
}
return list;
}
public static void main(String[] args) {
XmlParse p=new DomXmlParser();
String filename="e:\\1575355124731.xml";
//String filename="src/xml/books.xml";
List<Book> list=p.parseXml(filename);
System.out.println("DOM解析结果");
for(Book book:list)
{
System.out.println(book.toString());
}
}
}