Java生成和解析XML格式文件和字符串的实例代码
1、基础知识:
java解析xml一般有四种方法:dom、sax、jdom、dom4j。
2、使用介绍
1)、dom
(1)简介
由w3c(org.w3c.dom)提供的接口,它将整个xml文档读入内存,构建一个dom树来对各个节点(node)进行操作。优点就是整个文档都一直在内存中,我们可以随时访问任何节点,并且对树的遍历也是比较熟悉的操作;缺点则是耗内存,并且必须等到所有的文档都读入内存才能进行处理。
(2)示例代码:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<root>
<telephone>
<type name="nokia">
<price>599</price>
<operator>cmcc</operator>
</type>
<type name="xiaomi">
<price>699</price>
<operator>chinanet</operator>
</type>
</telephone>
</root>
import java.io.bytearrayoutputstream;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.stringreader;
import javax.xml.parsers.documentbuilder;
import javax.xml.parsers.documentbuilderfactory;
import javax.xml.parsers.parserconfigurationexception;
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.node;
import org.w3c.dom.nodelist;
import org.xml.sax.inputsource;
import org.xml.sax.saxexception;
public class xmlhandler {
public xmlhandler(){
}
public string createxml(){
string xmlstr = null;
documentbuilderfactory factory = documentbuilderfactory.newinstance();
try {
documentbuilder builder = factory.newdocumentbuilder();
document document = builder.newdocument();
document.setxmlversion("1.0");
element root = document.createelement("root");
document.appendchild(root);
element telephone = document.createelement("telephone");
element nokia = document.createelement("type");
nokia.setattribute("name", "nokia");
element pricenokia = document.createelement("price");
pricenokia.settextcontent("599");
nokia.appendchild(pricenokia);
element operatornokia = document.createelement("operator");
operatornokia.settextcontent("cmcc");
nokia.appendchild(operatornokia);
telephone.appendchild(nokia);
element xiaomi = document.createelement("type");
xiaomi.setattribute("name", "xiaomi");
element pricexiaomi = document.createelement("price");
pricexiaomi.settextcontent("699");
xiaomi.appendchild(pricexiaomi);
element operatorxiaomi = document.createelement("operator");
operatorxiaomi.settextcontent("chinanet");
xiaomi.appendchild(operatorxiaomi);
telephone.appendchild(xiaomi);
root.appendchild(telephone);
transformerfactory transfactory = transformerfactory.newinstance();
transformer transformer = transfactory.newtransformer();
domsource domsource = new domsource(document);
//export string
bytearrayoutputstream bos = new bytearrayoutputstream();
transformer.transform(domsource, new streamresult(bos));
xmlstr = bos.tostring();
//-------
//save as file
file file = new file("telephone.xml");
if(!file.exists()){
file.createnewfile();
}
fileoutputstream out = new fileoutputstream(file);
streamresult xmlresult = new streamresult(out);
transformer.transform(domsource, xmlresult);
//--------
} catch (parserconfigurationexception e) {
// todo auto-generated catch block
e.printstacktrace();
}catch (transformerconfigurationexception e) {
// todo auto-generated catch block
e.printstacktrace();
}catch (transformerexception e) {
// todo auto-generated catch block
e.printstacktrace();
}catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
return xmlstr;
}
public void parserxml(string strxml){
documentbuilderfactory factory = documentbuilderfactory.newinstance();
try {
documentbuilder builder = factory.newdocumentbuilder();
stringreader sr = new stringreader(strxml);
inputsource is = new inputsource(sr);
document doc = builder.parse(is);
element rootelement = doc.getdocumentelement();
nodelist phones = rootelement.getelementsbytagname("type");
for (int i = 0; i < phones.getlength(); i++) {
node type = phones.item(i);
string phonename = ((element)type).getattribute("name");
system.out.println("phone name = "+phonename);
nodelist properties = type.getchildnodes();
for (int j = 0; j < properties.getlength(); j++) {
node property = properties.item(j);
string nodename = property.getnodename();
if (nodename.equals("price")) {
string price=property.getfirstchild().getnodevalue();
system.out.println("price="+price);
} else if (nodename.equals("operator")) {
string operator=property.getfirstchild().getnodevalue();
system.out.println("operator="+operator);
}
}
}
} catch (parserconfigurationexception e) {
// todo auto-generated catch block
e.printstacktrace();
}catch (saxexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
public static void main(string[] args) {
xmlhandler handler = new xmlhandler();
string xml = handler.createxml();
system.out.println(xml);
handler.parserxml(xml);
}
}
(3)元素(element)和结点(node)的区别(org.w3c.dom)
node对象是整个文档对象模型的主要数据类型,是dom中最基本的对象,代表了文档树中的抽象节点。但在实际使用中很少会直接使用node对象,而是使用node对象的子对象element,attr,text等。
element对象表示html或xml文档中的一个元素,是node类最主要的子对象,在元素中可以包含属性,因而element中有存取其属性的方法。
element是从node继承而来的,元素是一个小范围的定义,必须是含有完整信息的结点才是一个元素,例如<div>...</div>。但是一个结点不一定是一个元素,而一个元素一定是一个结点。
node有几个子类型:element,text,attribute,rootelement,comment,namespace等
2)、sax
3)、jdom
4)、dom4j
(1)简介
dom4j是目前在xml解析方面是最优秀的(hibernate、sun的jaxm也都使用dom4j来解析xml),它合并了许多超出基本xml文档表示的功能,包括集成的xpath支持、xml schema支持以及用于大文档或流化文档的基于事件的处理。
在使用xpath时要增加jaxen.jar,否则会出现如下错误:
exception in thread "main" java.lang.noclassdeffounderror: org/jaxen/jaxenexception
at org.dom4j.documentfactory.createxpath(documentfactory.java:230)
at org.dom4j.tree.abstractnode.createxpath(abstractnode.java:207)
at org.dom4j.tree.abstractnode.selectnodes(abstractnode.java:164)
(2)示例代码:
import java.io.file;
import java.io.filewriter;
import java.io.ioexception;
import java.io.stringreader;
import java.io.stringwriter;
import java.util.list;
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;
import org.xml.sax.inputsource;
public class xmlhandler {
public xmlhandler() {
// todo auto-generated constructor stub
}
public string createxml(){
string strxml = null;
document document = documenthelper.createdocument();
element root = document.addelement("root");
element phone = root.addelement("telephone");
element nokia = phone.addelement("type");
nokia.addattribute("name", "nokia");
element price_nokia = nokia.addelement("price");
price_nokia.addtext("599");
element operator_nokia = nokia.addelement("operator");
operator_nokia.addtext("cmcc");
element xiaomi = phone.addelement("type");
xiaomi.addattribute("name", "xiaomi");
element price_xiaomi = xiaomi.addelement("price");
price_xiaomi.addtext("699");
element operator_xiaomi = xiaomi.addelement("operator");
operator_xiaomi.addtext("chinanet");
//--------
stringwriter strwtr = new stringwriter();
outputformat format = outputformat.createprettyprint();
format.setencoding("utf-8");
xmlwriter xmlwriter =new xmlwriter(strwtr, format);
try {
xmlwriter.write(document);
} catch (ioexception e1) {
// todo auto-generated catch block
e1.printstacktrace();
}
strxml = strwtr.tostring();
//--------
//-------
//strxml=document.asxml();
//------
//-------------
file file = new file("telephone.xml");
if (file.exists()) {
file.delete();
}
try {
file.createnewfile();
xmlwriter out = new xmlwriter(new filewriter(file));
out.write(document);
out.flush();
out.close();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
//--------------
return strxml;
}
public void parserxml(string strxml){
saxreader reader = new saxreader();
stringreader sr = new stringreader(strxml);
inputsource is = new inputsource(sr);
try {
document document = reader.read(is);
element root = document.getrootelement();
//get element
list<element> phonelist = root.elements("telephone");
list<element> typelist = phonelist.get(0).elements("type");
for (int i=0;i<typelist.size();i++){
element element = typelist.get(i);
string phonename = element.attributevalue("name");
system.out.println("phonename = "+phonename);
//get all element
list<element> childlist = element.elements();
for (int j=0;j<childlist.size();j++){
element e = childlist.get(j);
system.out.println(e.getname()+"="+e.gettext());
}
}
} catch (documentexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
public void parserxmlbyxpath(string strxml){
saxreader reader = new saxreader();
stringreader sr = new stringreader(strxml);
inputsource is = new inputsource(sr);
try {
document document = reader.read(is);
list list = document.selectnodes("/root/telephone/type");
for(int i=0;i<list.size();i++){
element e = (element) list.get(i);
system.out.println("phonename="+e.attributevalue("name"));
list list1 = e.selectnodes("./*");
for(int j=0;j<list1.size();j++){
element e1 = (element) list1.get(j);
system.out.println(e1.getname()+"="+e1.gettext());
}
}
} catch (documentexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
/**
* @param args
*/
public static void main(string[] args) {
// todo auto-generated method stub
xmlhandler handler = new xmlhandler();
string strxml=handler.createxml();
system.out.println(strxml);
handler.parserxml(strxml);
system.out.println("-----------");
handler.parserxmlbyxpath(strxml);
}
}
5)xpath
(1)简介
xpath是一门在xml文档中查找信息的语言。xpath用于在xml文档中通过元素和属性进行导航。
具体语法介绍参考:http://w3school.com.cn/xpath/index.asp
(2)示例代码:
import java.io.ioexception;
import java.io.stringreader;
import javax.xml.parsers.documentbuilder;
import javax.xml.parsers.documentbuilderfactory;
import javax.xml.parsers.parserconfigurationexception;
import javax.xml.xpath.xpath;
import javax.xml.xpath.xpathconstants;
import javax.xml.xpath.xpathexpression;
import javax.xml.xpath.xpathexpressionexception;
import javax.xml.xpath.xpathfactory;
import org.w3c.dom.document;
import org.w3c.dom.element;
import org.w3c.dom.node;
import org.w3c.dom.nodelist;
import org.xml.sax.inputsource;
import org.xml.sax.saxexception;
public class xmlhandler {
public xmlhandler() {
// todo auto-generated constructor stub
}
public void parserxml(string strxml){
documentbuilderfactory factory = documentbuilderfactory.newinstance();
try {
documentbuilder builder = factory.newdocumentbuilder();
stringreader sr = new stringreader(strxml);
inputsource is = new inputsource(sr);
document doc = builder.parse(is);
xpathfactory xfactory = xpathfactory.newinstance();
xpath xpath = xfactory.newxpath();
xpathexpression expr = xpath.compile("/root/telephone/type");
nodelist phones = (nodelist) expr.evaluate(doc, xpathconstants.nodeset);
for (int i = 0; i < phones.getlength(); i++) {
node type = phones.item(i);
string phonename = ((element)type).getattribute("name");
system.out.println("phone name = "+phonename);
xpathexpression expr1 = xpath.compile("./*");
nodelist list = (nodelist) expr1.evaluate(type, xpathconstants.nodeset);
for(int j =0;j<list.getlength();j++){
element e1 = (element) list.item(j);
system.out.println(e1.getnodename()+"="+e1.gettextcontent());
}
}
} catch (parserconfigurationexception e) {
// todo auto-generated catch block
e.printstacktrace();
}catch (saxexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}catch (xpathexpressionexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
/**
* @param args
*/
public static void main(string[] args) {
// todo auto-generated method stub
string strxml="<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>"+
"<root>"+
"<telephone>"+
"<type name=\"nokia\">"+
"<price>599</price>"+
"<operator>cmcc</operator>"+
"</type>"+
"<type name=\"xiaomi\">"+
"<price>699</price>"+
"<operator>chinanet</operator>"+
"</type>"+
"</telephone>"+
"</root>";
xmlhandler handler = new xmlhandler();
handler.parserxml(strxml);
}
}
ps:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:
在线xml/json互相转换工具:
在线格式化xml/在线压缩xml:
xml在线压缩/格式化工具: