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());
}
}