import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class XmlUtil
{
public static synchronized Document newDocument()
{
Document doc = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
doc = db.newDocument();
}
catch (Exception e)
{
LogUtil.logException( e );
}
return doc;
}
public static synchronized Element createRootElement()
{
Element rootElement = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
Document doc = db.newDocument();
rootElement = doc.getDocumentElement();
}
catch (Exception e)
{
e.printStackTrace();
}
return rootElement;
}
public static synchronized Element getRootElement(String fileName)
{
if (fileName == null || fileName.length() == 0)
{
return null;
}
try
{
Element rootElement = null;
FileInputStream fis = new FileInputStream(fileName);
rootElement = getRootElement(fis);
fis.close();
return rootElement;
}
catch (Exception e)
{
return null;
}
}
public static synchronized Element getRootElement(InputStream is)
{
if (is == null)
{
return null;
}
Element rootElement = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
Document doc = db.parse(is);
rootElement = doc.getDocumentElement();
}
catch (Exception e)
{
e.printStackTrace();
}
return rootElement;
}
public static synchronized Element getRootElement(InputSource is)
{
if (is == null)
{
return null;
}
Element rootElement = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
Document doc = db.parse(is);
rootElement = doc.getDocumentElement();
}
catch (Exception e)
{
e.printStackTrace();
}
return rootElement;
}
public static synchronized Element[] getChildElements(Element element)
{
if (element == null)
{
return null;
}
Vector childs = new Vector();
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Element)
{
childs.add( (Element)node);
}
}
Element[] elmt = new Element[childs.size()];
childs.toArray(elmt);
return elmt;
}
public static synchronized Element[] getChildElements(Element element,
String childName)
{
if (element == null || childName == null || childName.length() == 0)
{
return null;
}
Vector childs = new Vector();
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Element)
{
if (node.getNodeName().equals(childName))
{
childs.add( (Element)node);
}
}
}
Element[] elmt = new Element[childs.size()];
childs.toArray(elmt);
return elmt;
}
public static synchronized Node[] getChildNodes(Node node)
{
if (node == null)
{
return null;
}
Vector childs = new Vector();
for (Node n = node.getFirstChild(); n != null;
n = n.getNextSibling())
{
childs.add( (Element)n);
}
Node[] childNodes = new Element[childs.size()];
childs.toArray(childNodes);
return childNodes;
}
public static synchronized Element getChildElement(Element element,
String childName)
{
if (element == null || childName == null || childName.length() == 0)
{
return null;
}
Element childs = null;
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Element)
{
if (node.getNodeName().equals(childName))
{
childs = (Element)node;
break;
}
}
}
return childs;
}
public static synchronized Element getChildElement(Element element)
{
if (element == null)
{
return null;
}
Element childs = null;
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Element)
{
childs = (Element)node;
break;
}
}
return childs;
}
public static synchronized String[] getElenentValues(Element element)
{
if (element == null)
{
return null;
}
Vector childs = new Vector();
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Text)
{
childs.add(node.getNodeValue());
}
}
String[] values = new String[childs.size()];
childs.toArray(values);
return values;
}
public static synchronized String getElenentValue(Element element)
{
if (element == null)
{
return null;
}
String retnStr = null;
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Text)
{
String str = node.getNodeValue();
if (str == null || str.length() == 0
|| str.trim().length() == 0)
{
continue;
}
else
{
retnStr = str;
break;
}
}
}
return retnStr;
}
public static synchronized Element findElementByName(Element e, String name)
{
if (e == null || name == null || name.length() == 0)
{
return null;
}
String nodename = null;
Element[] childs = getChildElements(e);
for (int i = 0; i < childs.length; i++)
{
nodename = childs[i].getNodeName();
if (name.equals(nodename))
{
return childs[i];
}
}
for (int i = 0; i < childs.length; i++)
{
Element retn = findElementByName(childs[i], name);
if (retn != null)
{
return retn;
}
}
return null;
}
public static synchronized Element findElementByAttr(Element e, String attrName,
String attrVal)
{
return findElementByAttr( e, attrName, attrVal, true );
}
public static synchronized Element findElementByAttr(Element e, String attrName,
String attrVal, boolean dept)
{
if (e == null || attrName == null || attrName.length() == 0
|| attrVal == null || attrVal.length() == 0)
{
return null;
}
String tmpValue = null;
Element[] childs = getChildElements(e);
for (int i = 0; i < childs.length; i++)
{
tmpValue = childs[i].getAttribute(attrName);
if (attrVal.equals(tmpValue))
{
return childs[i];
}
}
if( dept )
{
for (int i = 0; i < childs.length; i++)
{
Element retn = findElementByAttr(childs[i], attrName, attrVal);
if (retn != null)
{
return retn;
}
}
}
return null;
}
public static synchronized String formatXml(Element e)
{
return formatXml(e, 0);
}
/**
* 格式化XML输出串.
*/
public static synchronized String formatXml(Element e, int indent)
{
indent++;
for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling())
{
appendIndent(e, n, indent);
if (!n.getNodeName().equals("#text"))
{
formatXml( (Element)n, indent);
}
}
indent--;
appendIndent(e, indent);
return e.toString();
}
/**
* 在指定的节点前插入格式表示.
*/
private static synchronized void appendIndent(Element e, Node pos, int indent)
{
Document doc = e.getOwnerDocument();
if (indent == 0)
{
e.insertBefore(doc.createTextNode("\n"), pos);
}
for (int i = 0; i < indent; i++)
{
if (i == 0)
{
e.insertBefore(doc.createTextNode("\n\t"), pos);
}
else
{
e.insertBefore(doc.createTextNode("\t"), pos);
}
}
}
/**
* 追加格式表示.
*/
private static synchronized void appendIndent(Element e, int indent)
{
Document doc = e.getOwnerDocument();
if (indent == 0)
{
e.appendChild(doc.createTextNode("\n"));
}
for (int i = 0; i < indent; i++)
{
if (i == 0)
{
e.appendChild(doc.createTextNode("\n\t"));
}
else
{
e.appendChild(doc.createTextNode("\t"));
}
}
}
public static synchronized void setAttribute(Element e, String name, String value)
{
if (e == null || name == null || name.length() == 0 || value == null
|| value.length() == 0)
return;
else
e.setAttribute( name, value );
}
public static synchronized String getAttribute(Element e, String name)
{
return getAttribute( e, name, null );
}
public static synchronized String getAttribute(Element e, String name, String defval)
{
if( e == null || name == null || name.length()== 0 )
return defval;
else
return e.getAttribute(name);
}
public void transformerWrite( Element doc, String filename ) throws Exception
{
DOMSource doms = new DOMSource( doc );
File f = new File( filename );
StreamResult sr = new StreamResult( f );
transformerWrite( doms, sr );
}
public void transformerWrite( Element doc, File file ) throws Exception
{
DOMSource doms = new DOMSource( doc );
StreamResult sr = new StreamResult( file );
transformerWrite( doms, sr );
}
public void transformerWrite( Element doc, OutputStream outstream ) throws Exception
{
DOMSource doms = new DOMSource( doc );
StreamResult sr = new StreamResult( outstream );
transformerWrite( doms, sr );
}
public void transformerWrite( Element doc, Writer outwriter ) throws Exception
{
DOMSource doms = new DOMSource( doc );
StreamResult sr = new StreamResult( outwriter );
transformerWrite( doms, sr );
}
public void transformerWrite( DOMSource doms, StreamResult sr ) throws Exception
{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty( OutputKeys.ENCODING, "GBK" );
t.transform( doms, sr );
}
}
XML工具类
package com.company.cpc.offlinelog.dao;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
//需要引用castor.jar文件
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.xml.sax.InputSource;
import com.zte.ecc.util.tracer.Debug;
/**
* 类 名 称:XmlFileManager
* 内容摘要:该类是XML工具类
*/
public class XmlFileManager {
/**
* 方法名称:objectListToXMLString
* 内容摘要:把对象编组成XML
* @param mappingXMLString 映射的XML串
* @param containerClass 编组类
* @return String 返回XML
* @throws IOException
* @throws MappingException
* @throws MarshalException
* @throws ValidationException
*/
public static String objectListToXMLString(
String mappingXMLString,
Object containerClass)
throws IOException, MappingException, MarshalException, ValidationException {
if (containerClass == null) {
Debug.println("containerClass is NULL!!!!!");
return "";
}
//准备Mapping
Mapping mapping = new Mapping();
Reader reader = new StringReader(mappingXMLString);
InputSource is = new InputSource(reader);
mapping.loadMapping(is);
//准备Writer
StringWriter writer = new StringWriter();
Marshaller marshaller = new Marshaller(writer);
//开始编组
marshaller.setMapping(mapping);
marshaller.setEncoding("gb2312");
marshaller.marshal(containerClass);
StringBuffer bf = writer.getBuffer();
writer.close();
return bf.toString();
}
/**
*
* 方法名称:XmlToObjectList
* 内容摘要:把XML解组成对象
* @param mappingXMLString 映射的XML串
* @param xmlString 描述数据的XML串
* @return Object
* @throws IOException
* @throws MappingException
* @throws MarshalException
* @throws ValidationException
*/
public static Object XmlToObjectList(
String mappingXMLString,
String xmlString)
throws IOException, MappingException, MarshalException, ValidationException {
//准备Mapping
StringReader mapingReader = new StringReader(mappingXMLString);
InputSource is = new InputSource(mapingReader);
Mapping mapping = new Mapping();
mapping.loadMapping(is);
//准备Reader
Reader reader = new StringReader(xmlString);
//开始解组
Unmarshaller unmarshaller = new Unmarshaller(mapping);
Object containerClass = unmarshaller.unmarshal(reader);
reader.close();
return containerClass;
}
/**
*
* 方法名称:saveToXMLFile
* 内容摘要:把对象编组成XML文件
* @param xmlFileName 文件名
* @param mappingFileName 映射文件名
* @param containerClass
* @throws IOException
* @throws MappingException
* @throws MarshalException
* @throws ValidationException
*/
public static void saveToXMLFile(
String xmlFileName,
String mappingFileName,
Object containerClass)
throws IOException, MappingException, MarshalException, ValidationException {
if (containerClass == null) {
Systen.out.println("containerClass is NULL!!!!!");
return;
}
//准备Mapping
Mapping mapping = new Mapping();
mapping.loadMapping(mappingFileName);
//准备Writer
File file = new File(xmlFileName);
Writer writer = new FileWriter(file);
Marshaller marshaller = new Marshaller(writer);
//开始编组
marshaller.setMapping(mapping);
marshaller.setEncoding("gb2312");
marshaller.marshal(containerClass);
writer.close();
}
/**
*
* 方法名称:loadFromXMLFile
* 内容摘要:把XML文件解组成对象
* @param xmlFileName
* @param mappingFileName
* @return
* @throws IOException
* @throws MappingException
* @throws MarshalException
* @throws ValidationException
*/
public static Object loadFromXMLFile(
String xmlFileName,
String mappingFileName)
throws IOException, MappingException, MarshalException, ValidationException {
//准备Mapping
Mapping mapping = new Mapping();
mapping.loadMapping(mappingFileName);
//准备Reader
Reader reader = new FileReader(xmlFileName);
//开始解组
Unmarshaller unmarshaller = new Unmarshaller(mapping);
Object containerClass = unmarshaller.unmarshal(reader);
reader.close();
return containerClass;
}
/**
*
* 方法名称:readerToString
* 内容摘要:把Reader流中的数据变为字符串
* @param reader
* @param bfferSize
* @return
*/
public static String readerToString(Reader reader, int bfferSize) {
StringBuffer sb = new StringBuffer();
char[] b = new char[bfferSize];
int n = 0;
try {
while ((n = reader.read(b)) > 0) {
System.out.println("read:" + n);
sb.append(b, 0, n);
}
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return sb.toString();
}
/**
* 方法名称:objectListToXMLString
* 内容摘要:把对象编组成XML
* @param mappingFileName 映射文件名
* @param containerClass 编组类
* @return String 返回XML
* @throws IOException
* @throws MappingException
* @throws MarshalException
* @throws ValidationException
*/
public static String objectListToXMLStr(
String mappingFileName,
Object containerClass)
throws IOException, MappingException, MarshalException, ValidationException {
if (containerClass == null) {
Debug.println("containerClass is NULL!!!!!");
return "";
}
//准备Mapping
Mapping mapping = new Mapping();
mapping.loadMapping(mappingFileName);
//准备Writer
StringWriter writer = new StringWriter();
Marshaller marshaller = new Marshaller(writer);
//开始编组
marshaller.setMapping(mapping);
marshaller.setEncoding("gb2312");
marshaller.marshal(containerClass);
StringBuffer bf = writer.getBuffer();
writer.close();
return bf.toString();
}
/**
*
* 方法名称:XmlToObjectList
* 内容摘要:把XML解组成对象
* @param mappingFileName 映射文件名
* @param xmlString 描述数据的XML串
* @return
* @throws IOException
* @throws MappingException
* @throws MarshalException
* @throws ValidationException
*/
public static Object XmlStrToObjectList(
String mappingFileName,
String xmlString)
throws IOException, MappingException, MarshalException, ValidationException {
//准备Mapping
Mapping mapping = new Mapping();
mapping.loadMapping(mappingFileName);
//准备Reader
Reader reader = new StringReader(xmlString);
//开始解组
Unmarshaller unmarshaller = new Unmarshaller(mapping);
Object containerClass = unmarshaller.unmarshal(reader);
reader.close();
return containerClass;
}
/**
* 方法名称:XmlToObjectList
* 内容摘要:得到资源文件的绝对路径文件名
* @param sResourceName 资源名称
* @return String
*/
public static String getResourceFilePath(String sResourceName) {
if (!sResourceName.startsWith("/")) {
sResourceName = "/" + sResourceName;
}
java.net.URL classUrl = XmlFileManager.class.getResource(sResourceName);
if (classUrl == null) {
System.out.println(
"\nResource '"
+ sResourceName
+ "' not found in \n'"
+ System.getProperty("java.class.path")
+ "'");
return null;
} else {
System.out.println(
"\nResource '"
+ sResourceName
+ "' found in \n'"
+ classUrl.getFile()
+ "'");
return classUrl.getFile();
}
}
}
需要一些jar,自己去down吧
/*
* created by intellij idea.
* user: administrator
* date: mar 26, 2002
* time: 1:24:56 pm
* to change template for new class use
* code style | class templates options (tools | ide options).
*/
/***** readxml.java **********************
*this is a javabean.
*this bean read a xml file from a url,and return a xmldom
*
***** created by xiao yusong 2001-11-30 ****
*/
package com.chinacountry.util;
import java.util.*;
import java.net.url;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
import org.apache.xml.serialize.outputformat;
import org.apache.xml.serialize.serializer;
import org.apache.xml.serialize.serializerfactory;
import org.apache.xml.serialize.xmlserializer;
import org.xml.sax.inputsource;
public class xmlutil implements java.io.serializable {
public xmlutil()
{
}
public static documentbuilder getbuilder() throws parserconfigurationexception
{
documentbuilder builder=documentbuilderfactory.newinstance().newdocumentbuilder();
return builder;
}
//get a document from given file
public static document getdocument(string path) throws exception
{
//bufferedreader filein=new bufferedreader(new filereader(path));
file f = new file(path);
documentbuilder builder=getbuilder();
document doc = builder.parse(f);
return doc;
}
//get a document from inputstream
public static document getdocument(inputstream in) throws exception
{
documentbuilder builder=getbuilder();
document doc = builder.parse(in);
return doc;
}
//create a empty document
public static document getnewdoc() throws exception
{
documentbuilder builder=getbuilder();
document doc = builder.newdocument();
return doc;
}
//create a document from given string
public static document getnewdoc(string xmlstr)
{
document doc = null;
try
{
stringreader sr = new stringreader(xmlstr);
inputsource isrc = new inputsource(sr);
documentbuilder builder=getbuilder();
doc = builder.parse(isrc);
}
catch (exception ex)
{
ex.printstacktrace();
}
return doc;
}
//save a document as a file at the given file path
public static void save(document doc, string filepath)
{
try
{
outputformat format = new outputformat(doc); //serialize dom
format.setencoding("gb2312");
stringwriter stringout = new stringwriter(); //writer will be a string
xmlserializer serial = new xmlserializer(stringout, format);
serial.asdomserializer(); // as a dom serializer
serial.serialize(doc.getdocumentelement());
string strxml = stringout.tostring(); //spit out dom as a string
string path = filepath;
writexml(strxml, path);
}
catch (exception e)
{
e.printstacktrace();
}
}
//save a string(xml) in the given file path
public static void writexml(string strxml, string path)
{
try
{
file f = new file(path);
printwriter out = new printwriter(new filewriter(f));
out.print(strxml + "\n");
out.close();
}
catch (ioexception e)
{
e.printstacktrace();
}
}
//format a document to string
public static string tostring(document doc)
{
string strxml = null;
try
{
outputformat format = new outputformat(doc); //serialize dom
format.setencoding("gb2312");
stringwriter stringout = new stringwriter(); //writer will be a string
xmlserializer serial = new xmlserializer(stringout, format);
serial.asdomserializer(); // as a dom serializer
serial.serialize(doc.getdocumentelement());
strxml = stringout.tostring(); //spit out dom as a string
}
catch (exception e)
{
e.printstacktrace();
}
return strxml;
}
//format a node to string
public static string tostring(node node, document doc)
{
string strxml = null;
try
{
outputformat format = new outputformat(doc); //serialize dom
format.setencoding("gb2312");
stringwriter stringout = new stringwriter(); //writer will be a string
xmlserializer serial = new xmlserializer(stringout, format);
serial.asdomserializer(); // as a dom serializer
serial.serialize((element) node);
strxml = stringout.tostring(); //spit out dom as a string
}
catch (exception e)
{
e.printstacktrace();
}
return strxml;
}
public static void main(string[] args) throws exception
{
string pathroot = "netrees.xml";
document doc,doc1;
try
{
doc = xmlutil.getdocument(pathroot);
doc1 = xmlutil.getdocument(pathroot);
if(doc == doc1)
{
system.out.println("they are same objects!");
}
else
{
system.out.println("they are different!");
outputformat format = new outputformat(doc); //serialize dom
format.setencoding("gb2312");
stringwriter stringout = new stringwriter(); //writer will be a string
xmlserializer serial = new xmlserializer(stringout, format);
serial.asdomserializer(); // as a dom serializer
serial.serialize(doc.getdocumentelement());
string strxml = stringout.tostring(); //spit out dom as a string
system.out.println(strxml);
}
}
catch (exception ex)
{
system.out.print("reading file\"" + pathroot + "\" error!");
ex.printstacktrace();
}
}
}
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ObjectToXMLUtil
{
/**
* 把java的可序列化的对象(实现Serializable接口)序列化保存到XML文件里面,如果想一次保存多个可序列化对象请用集合进行封装
* 保存时将会用现在的对象原来的XML文件内容
* @param obj 要序列化的可序列化的对象
* @param fileName 带完全的保存路径的文件名
* @throws FileNotFoundException 指定位置的文件不存在
* @throws IOException 输出时发生异常
* @throws Exception 其他运行时异常
*/
public static void objectXmlEncoder(Object obj,String fileName)
throws FileNotFoundException,IOException,Exception
{
//创建输出文件
File fo = new File(fileName);
//文件不存在,就创建该文件
if(!fo.exists())
{
//先创建文件的目录
String path = fileName.substring(0,fileName.lastIndexOf('.'));
File pFile = new File(path);
pFile.mkdirs();
}
//创建文件输出流
FileOutputStream fos = new FileOutputStream(fo);
//创建XML文件对象输出类实例
XMLEncoder encoder = new XMLEncoder(fos);
//对象序列化输出到XML文件
encoder.writeObject(obj);
encoder.flush();
//关闭序列化工具
encoder.close();
//关闭输出流
fos.close();
}
/**
* 读取由objSource指定的XML文件中的序列化保存的对象,返回的结果经过了List封装
* @param objSource 带全部文件路径的文件全名
* @return 由XML文件里面保存的对象构成的List列表(可能是一个或者多个的序列化保存的对象)
* @throws FileNotFoundException 指定的对象读取资源不存在
* @throws IOException 读取发生错误
* @throws Exception 其他运行时异常发生
*/
public static List objectXmlDecoder(String objSource)
throws FileNotFoundException,IOException,Exception
{
List objList = new ArrayList();
File fin = new File(objSource);
FileInputStream fis = new FileInputStream(fin);
XMLDecoder decoder = new XMLDecoder(fis);
Object obj = null;
try
{
while( (obj = decoder.readObject()) != null)
{
objList.add(obj);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
}
fis.close();
decoder.close();
return objList;
}
}