java导出xml
Ⅰ 用java怎么把String类型的字符串转化为XML格式输出
java中将string转换成xml文件,使用开源jar包 dom4j:
packagecom.webdesk.swing.powertable.util;
importjava.io.ByteArrayInputStream;
importjava.io.File;
importjava.io.FileWriter;
importjava.io.IOException;
importorg.dom4j.Document;
importorg.dom4j.DocumentException;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.SAXReader;
importorg.dom4j.io.XMLWriter;
publicclassXmlUtil{
(StringfileName){
try{
SAXReadersaxReader=newSAXReader();//新建一个解析类
DocumenttempDocument=saxReader.read(XmlUtil.class.getClassLoader().getResourceAsStream(fileName));//读入一个文件
returntempDocument.asXML();
}catch(DocumentExceptione){
e.printStackTrace();
}
returnnull;
}
//将字符串string类型转换成xml文件
publicstaticvoidstrChangeXML(Stringstr)throwsIOException{
SAXReadersaxReader=newSAXReader();
Documentdocument;
try{
document=saxReader.read(newByteArrayInputStream(str.getBytes("UTF-8")));
OutputFormatformat=OutputFormat.createPrettyPrint();
/**将document中的内容写入文件中*/
XMLWriterwriter=newXMLWriter(newFileWriter(newFile("src/com/webdesk/swing/powertable/digester/cctv.xml")),format);
writer.write(document);
writer.close();
}catch(DocumentExceptione){
e.printStackTrace();
}
}
}
Ⅱ JAVA中将数据导出成XML文件(急急急急)
2./**
1. * desciption:java create xml file
2. * author:maomao
3. * datetime:2007/04/04 23:42
4. */
5.
6.package com.xh.xml;
1.
2.import java.io.FileOutputStream;
1.import java.io.IOException;
1.import org.jdom.Document;
1.import org.jdom.Element;
1.import org.jdom.JDOMException;
1.import org.jdom.output.XMLOutputter;
1.
2.public class Java2XML {
1.
2. public void BuildXMLDoc() throws IOException, JDOMException {
3.
4. // 创建根节点 list;
5. Element root = new Element("list");
6.
7. // 根节点添加到文档中;
8. Document Doc = new Document(root);
9.
10. // 此处 for 循环可替换成 遍历 数据库表的结果集操作;
11. for (int i = 0; i < 5; i++) {
12.
13. // 创建节点 user;
14. Element elements = new Element("user");
15.
16. // 给 user 节点添加属性 id;
17. elements.setAttribute("id", "" + i);
18.
19. // 给 user 节点添加子节点并赋值;
20. // new Element("name")中的 "name" 替换成表中相应字段,setText("xuehui")中 "xuehui 替换成表中记录值;
21. elements.addContent(new Element("name").setText("xuehui"));
22. elements.addContent(new Element("age").setText("28"));
23. elements.addContent(new Element("sex").setText("Male"));
24.
25. // 给父节点list添加user子节点;
26. root.addContent(elements);
27.
28. }
29. XMLOutputter XMLOut = new XMLOutputter();
30.
31. // 输出 user.xml 文件;
32. XMLOut.output(Doc, new FileOutputStream("user.xml"));
33. }
34.
35. public static void main(String[] args) {
36. try {
37. Java2XML j2x = new Java2XML();
38. System.out.println("生成 mxl 文件...");
39. j2x.BuildXMLDoc();
40. } catch (Exception e) {
41. e.printStackTrace();
42. }
43. }
44.
45.}
生成结果:
# <?xml version="1.0" encoding="UTF-8"?>
# <list>
# <user id="0">
# <name>xuehui</name>
# <age>28</age>
# <sex>Male</sex>
# </user>
# <user id="1">
# <name>xuehui</name>
# <age>28</age>
# <sex>Male</sex>
# </user>
# <user id="2">
# <name>xuehui</name>
# <age>28</age>
# <sex>Male</sex>
# </user>
# <user id="3">
# <name>xuehui</name>
# <age>28</age>
# <sex>Male</sex>
# </user>
# <user id="4">
# <name>xuehui</name>
# <age>28</age>
# <sex>Male</sex>
# </user>
# </list>
你可以参考一下链接,然后拷贝代码,这里我直接拷贝带上行号。
Ⅲ 如何用Java实现对xml文件的读取和写入以及保存
直接附源码import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;import org.dom4j.*;
import org.dom4j.io.XMLWriter;
public class Dom4jSample { public static void main(String[] args) {
Dom4jSample dom4jSample = new Dom4jSample();
Document document = dom4jSample.createDocument();
try{
dom4jSample.FileWrite(document);
Document documentStr = dom4jSample.StringToXML("<China>I Love!</China>");
dom4jSample.XMLWrite(documentStr);
Element legend = dom4jSample.FindElement(document);
System.out.println(legend.getText());
}
catch(Exception e)
{
}
}
/*
* Create a XML Document
*/
public Document createDocument()
{
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
Element author1 = root.addElement("Lynch");
author1.addAttribute("Age","25");
author1.addAttribute("Country","China");
author1.addText("I am great!");
Element author2 = root.addElement("Legend");
author2.addAttribute("Age","25");
author2.addAttribute("Country","China");
author2.addText("I am great!too!");
return document;
}
/*
* Create a XML document through String
*/
public Document StringToXML(String str) throws DocumentException
{
Document document = DocumentHelper.parseText(str);
return document;
}
public Element FindElement(Document document)
{
Element root = document.getRootElement();
Element legend = null;
for(Iterator i=root.elementIterator("legend");i.hasNext();)
{
legend = (Element)i.next();
}
return legend;
}
/*
* Write a XML file
*/
public void FileWrite(Document document) throws IOException
{
FileWriter out = new FileWriter("C:/Dom2jSample.xml");
document.write(out);
out.close();
}
/*
* Write a XML format file
*/
public void XMLWrite(Document document) throws IOException
{
XMLWriter writer = new XMLWriter(new FileWriter("C:/Dom2jSampleStr.xml"));
writer.write(document);
writer.close();
}
}
Ⅳ java镐庝箞镎崭綔excel杞瑇ml鏂囦欢java瀹炵幇excel杞瑆ord
銆銆锏惧害鎼灭储鍦圱绀惧尯 鍏嶈垂琛屼笟瑙嗛戞暀绋www.aiquanti.com
銆銆package com.asima;
銆銆import java.io.FileInputStream;
銆銆import java.sql.Connection;
銆銆import java.sql.DriverManager;
銆銆import java.sql.PreparedStatement;
銆銆import org.apache.poi.hssf.usermodel.HSSFCell;
銆銆import org.apache.poi.hssf.usermodel.HSSFRow;
銆銆import org.apache.poi.hssf.usermodel.HSSFSheet;
銆銆import org.apache.poi.hssf.usermodel.HSSFWorkbook;
銆銆/**
銆銆*
銆銆* @author asima
銆銆* @data 2006-10-18
銆銆*/
銆銆public class XlsToAccess
銆銆{
銆銆HSSFSheet globalSheet = null;
銆銆/*璇诲彇涓涓鎸囧畾鍗曞厓镙煎唴瀹*/
銆銆public String readCellValue(String pos)
銆銆{
銆銆int xpos;
銆銆short ypos;
銆銆int cellType; /*鍙栧缑姝ゅ崟鍏冩牸镄勭被鍨 0-Numeric,1-String;
銆銆3-null*/
銆銆String result; /*杩斿洖鍙栧缑镄勫崟鍏冩牸镄勫*/
銆銆ypos = (short) (pos.toUpperCase().charAt(0) - 65);
銆銆xpos = Integer.parseInt(pos.substring(1, pos.length())) - 1;
銆銆HSSFRow row = null; /* 瀹氢箟excel涓镄勮 */
銆銆HSSFCell cell = null; /* 瀹氢箟excel涓镄勫崟鍏冩牸 */
銆銆/* 镙规嵁xPos鍜寉Pos鍙栧缑鍗曞厓镙 */
銆銆row = globalSheet.getRow(xpos);
銆銆cell = row.getCell(ypos);
銆銆/** **************姝ゅ勫傛灉鏄绌洪渶瑕佷慨鏀********************************** */
銆銆cellType = cell.getCellType();
銆銆switch (cellType)
銆銆{
銆銆case 0: /* 0-Numeric */
銆銆result = String.valueOf(cell.getNumericCellValue());
銆銆break;
銆銆case 1: /* 1-String */
銆銆result = cell.getStringCellValue();
銆銆break;
銆銆case 3: /* 3-null */
銆銆result = \"\";
銆銆break;
銆銆default:
銆銆result = \"\";
銆銆break;
銆銆}
銆銆return result;
銆銆}
銆銆/*璇诲彇excel鏂囦欢骞舵妸鍐呭规彃鍏ュ埌access琛ㄤ腑*/
銆銆public void insertIntoTable() throws Exception
銆銆{
銆銆// 鍒涘缓瀵笶xcel宸ヤ綔绨挎枃浠剁殑寮旷敤
銆銆HSSFWorkbook workbook =
銆銆new HSSFWorkbook(new FileInputStream(\"D:/temp/test.xls\"));
銆銆// 銮峰缑涓涓狲heet
銆銆globalSheet = workbook.getSheetAt(0);
銆銆String value1 = readCellValue(\"c1\");
銆銆String value2 = readCellValue(\"c2\");
銆銆String value3 = readCellValue(\"c3\");
銆銆String value4 = readCellValue(\"c4\");
銆銆System.out.println(value1);
銆銆System.out.println(value2);
銆銆/* 鎻掑叆鏁版嵁搴 */
銆銆Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");
銆銆String url = \"jdbc:odbc:asima\";
銆銆Connection conn = DriverManager.getConnection(url);
銆銆PreparedStatement stmt =
銆銆conn.prepareStatement(\"insert into custom values(?,?,?,?)\");
銆銆// 瀹氢箟镆ヨ㈢殑SQL璇鍙
銆銆stmt.setString(1, value1);
銆銆stmt.setString(2, value2);
銆銆stmt.setString(3, value3);
銆銆stmt.setString(4, value4);
銆銆stmt.executeUpdate
銆銆涓嬭浇jdom-2.0.6.jar鍜屾搷浣渆xcel镄刯xl-2.6.jar
銆銆/**
銆銆* 灏唀xecl杞鎴恱ml
銆銆*
銆銆* @param excelPath
銆銆*琚杞鎹㈢殑excel鏂囦欢璺寰
銆銆* @param xmlPath
銆銆*杞鎹㈡垚xml镄勮矾寰
銆銆*/
銆銆public static void execlConvertXml(String excelPath, String xmlPath) {
銆銆Workbook readwb = null;
銆銆try {
銆銆readwb = Workbook.getWorkbook(new File(excelPath));
銆銆Element data = new Element(\"data\");// 鍒涘缓镙硅妭镣
銆銆Document doc = new Document(data);// 镙硅妭镣规坊锷犲埌鏂囨。涓;
銆銆// 寰鐜姣忎釜sheet
銆銆for (int m = 0; m < readwb.getNumberOfSheets(); m++) {
銆銆Sheet sheet = readwb.getSheet(m);
銆銆int rsColumns = sheet.getColumns();// 銮峰彇Sheet琛ㄤ腑镓鍖呭惈镄勬诲垪鏁
銆銆int rsRows = sheet.getRows();// 銮峰彇Sheet琛ㄤ腑镓鍖呭惈镄勬昏屾暟
銆銆Cell[] firstCells = sheet.getRow(0);// 銮峰彇姣忎釜sheet涓镄勭涓琛屾爣棰
銆銆// 寰鐜姣忚岋纴浠1琛屽紑濮1寮濮嬶纴绗0琛屼负鍒楀悕
銆銆for (int i = 1; i < rsRows; i++) {
銆銆// 鍒涘缓琛岃妭镣;
銆銆Element row = new Element(\"dataDetail\");
銆銆insertHead(row);// 姣忎竴琛屾坊锷犵浉钖岀殑淇℃伅锛屽彲蹇界暐
銆銆// 寰鐜褰揿墠琛岀殑钖勫崟鍏冩牸
銆銆for (int j = 1; j < rsColumns; j++) {
銆銆Cell cell = sheet.getCell(j, i);// 鍙栧嚭姣忎釜鍗曞厓镙
銆銆if (cell.getContents() == \"\") {
銆銆continue;
銆銆}
銆銆Element column = new Element(
銆銆firstCells[j].getContents());// 鍒涘缓鍗曞厓镙艰妭镣
銆銆column.setText(cell.getContents());
銆銆row.addContent(column);
銆銆}
銆銆data.addContent(row);
銆銆}
銆銆}
銆銆// 灏嗘爣绛惧唴瀹规牸寮忓寲
銆銆Format format = Format.getPrettyFormat();
銆銆XMLOutputter XMLOut = new XMLOutputter(format);
銆銆XMLOut.output(doc, new FileOutputStream(xmlPath));
銆銆} catch (Exception e) {
銆銆e.printStackTrace();
銆銆} finally {
銆銆readwb.close();
銆銆System.out.println(\"run over\");
銆銆}
銆銆}
Ⅳ java怎么将数据导出为xml文件
给你一个将数据库中表格生成xml文件的简单例子,希望对你有帮助
package book;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class SqlBean {
Connection con=null;
PreparedStatement stmt=null;
ResultSet rs=null;
public SqlBean()
{
try
{
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con=DriverManager.getConnection("","","");
stmt=con.prepareStatement("select * from book order by id");
}catch(Exception e)
{
e.printStackTrace();
}
}
public int JdomParser(){
this.query();
int m=1;
try{
Element root,book,bookname,author,price;
root=new Element("BookHome");
Document doc=new Document(root);
ResultSetMetaData rsmd=rs.getMetaData();
int colCount=rsmd.getColumnCount();
while(rs.next())
{
book=new Element("book");
bookname=new Element(rsmd.getColumnName(2));
author=new Element(rsmd.getColumnName(3));
price=new Element(rsmd.getColumnName(4));
bookname.setText(rs.getString(2));
author.setText(rs.getString(3));
price.setText(rs.getString(4));
book.addContent(bookname);
book.addContent(author);
book.addContent(price);
book.setAttribute(rsmd.getColumnName(1), rs.getString(1));
root.addContent(book);
}
Format format=Format.getCompactFormat();
format.setEncoding("gb2312");
format.setIndent(" ");
XMLOutputter XMLOut=new XMLOutputter(format);
XMLOut.output(doc, new FileOutputStream("D:/workspace/XML/book.xml"));
m=0;
}catch(Exception e){
e.printStackTrace();
}
finally
{
this.close();
}
return m;
}
public ResultSet query()
{
try{
rs=stmt.executeQuery();
}catch(Exception e){
e.printStackTrace();
}
return rs;
}
public void close()
{
try{
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
Ⅵ 大家好,请教Java高手,Java生成xml文件
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import javax.swing.JOptionPane;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
public class Test20 {
public static void main(String[] args) throws Exception {
Document dom=DocumentHelper.createDocument();//创建xml文件
Element root=dom.addElement("url");//添加根元素,Xval
Element data=root.addElement("data");
data.setText("淘宝");
Element licence=root.addElement("Licence");
licence.setText("免费软件");
String xml=dom.asXML();
System.out.println(xml);
File f=new File("d:/xml.xml");
PrintWriter pw=new PrintWriter(f);
pw.write(xml);
pw.close();
JOptionPane.showMessageDialog(null, "已生成xml文件,路径为为d:/xml.xml");
}
}
用的是dom4j,见附件,
Have Fun
Ⅶ 怎么使用java导出大数据为xml文件
dom4j可以试试,不知道你的数据量有多大,如果太大的话,我没试过
xml文件是有规律的,你可以把要导出的数据构造一下,
我有个简单的代码
packagecom.test.xml;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.io.Writer;
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
importorg.dom4j.io.OutputFormat;
importorg.dom4j.io.XMLWriter;
publicclassDom4JXML{
publicvoidcreateXML(){
//用工厂类创建一个document实例
Documentdoc=DocumentHelper.createDocument();
//创建根元素emps
ElementrootEle=doc.addElement("emps");
//添加注释
rootEle.addComment("这是一个dom4j生成的xml文件");
//emps根节点下创建一个emp节点
ElementempEle=rootEle.addElement("emp");
//emp添加属性id="1"
empEle.addAttribute("id","1");
//emp节点下创建一个name节点
ElementnameEle=empEle.addElement("name");
//name节点下创建一个文本节点zhangsan
nameEle.setText("zhangsan");
//再为name节点创建一个兄弟节点
ElementsexEle=empEle.addElement("sex");
sexEle.setText("man");
//将document中的内容写入文件中
try{
Writerout=newFileWriter("F:\emps.xml");
//格式化输出,类型IE浏览一样
OutputFormatformat=OutputFormat.createPrettyPrint();
//OutputFormatformat=OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
//创建写出对象
XMLWriterwriter=newXMLWriter(out,format);
writer.write(doc);
writer.close();
System.out.println("生成emps.xml成功。");
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
System.out.println("失败了。");
}
}
publicstaticvoidmain(String[]args){
newDom4JXML().createXML();
}
}
然而从xml文件中解析以后的数据收集可以用SAX试试看
我这里有个简单的例子
packagecom.test.xml;
importorg.xml.sax.Attributes;
importorg.xml.sax.SAXException;
importorg.xml.sax.helpers.DefaultHandler;
{
publicvoidstartDocument()throwsSAXException{
System.out.println("起始文挡");
}
publicvoidendDocument()throwsSAXException{
System.out.println("结束文挡");
}
publicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{
StringcharString=newString(ch,start,length);
System.out.println("字符:"+charString);
}
publicvoidstartElement(StringnamespaceURI,StringlocalName,StringqName,Attributesatts)throwsSAXException{
System.out.println("起始元素:"+qName);
for(inti=0;i<atts.getLength();i++){
System.out.println("属性值:"+atts.getValue(i));
}
}
publicvoidendElement(StringnamespaceURI,StringlocalName,StringqName)throwsSAXException{
System.out.println("结束元素:"+qName);
}
}
packagecom.test.xml;
importjavax.xml.parsers.SAXParser;
importjavax.xml.parsers.SAXParserFactory;
publicclassBooks{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args)throwsException{
//TODO自动生成方法存根
SAXParserFactoryfactory=SAXParserFactory.newInstance();
SAXParserparser=factory.newSAXParser();
parser.parse("booksamp.xml",newSAXParseHandler());
}
}