日期:2014-05-20 浏览次数:20706 次
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* 用dom4j生成条形码的XML格式:
* <barcodeInfo>
<barcodeString>1231231</barcodeString>
<writeTimeString>2012-3-13 13:23:32</writeTimeString>
</barcodeInfo>
* @author wfg
*/
public class DOM4jXML {
/**
*
* @param 文件名(XXX.xml)
* @param Str 字符串
* @param timeStr 时间字符串
*/
public static void createBarcodeXml(String fileName,String barcodeStr,String timeStr)
{
Document document = DocumentHelper.createDocument(); //创建文档
Element barcodeInfo=document.addElement("barcodeInfo");
Element barcodeString=barcodeInfo.addElement("barcodeString");
Element writeTime=barcodeInfo.addElement("writeTimeString");
barcodeString.setText(barcodeStr);
writeTime.setText(timeStr);
try {
Writer fileWriter=new FileWriter(fileName);
XMLWriter xmlWriter=new XMLWriter(fileWriter);
xmlWriter.write(document); //写入文件中
xmlWriter.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
/**
* 读取xml文件
* @param fileName
*/
void parserXml(String fileName)
{
File inputXml=new File(fileName);
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(inputXml); //把文件读入到文档
Element barcodeInfo=document.getRootElement(); //获取文档根节点
this.doublexml(barcodeInfo);
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
}
private void doublexml(Element ele)
{
StringBuilder sb = new StringBuilder();
for(Iterator i = ele.elementIterator();i.hasNext();)
{
Element node = (Element)i.next();