導航:首頁 > 編程語言 > java字元串生成xml

java字元串生成xml

發布時間:2024-08-20 14:50:33

❶ 我想生成一個xml ,用java ,但不知道參數有多少個。方法應該怎麼寫

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;

public class Test {
public static void main(String[] args) {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
Element theBook=null, theElem=null, root=null;
try {
factory.(true);

DocumentBuilder db=factory.newDocumentBuilder();
Document xmldoc=db.parse(new File("Test1.xml"));
root=xmldoc.getDocumentElement();

//--- 新建一本書開始 ----
theBook=xmldoc.createElement("book");
theElem=xmldoc.createElement("name");
theElem.setTextContent("新書");
theBook.appendChild(theElem);

theElem=xmldoc.createElement("price");
theElem.setTextContent("20");
theBook.appendChild(theElem);

theElem=xmldoc.createElement("memo");
theElem.setTextContent("新書的更好看。");
theBook.appendChild(theElem);
root.appendChild(theBook);
System.out.println("--- 新建一本書開始 ----");
output(xmldoc);
//--- 新建一本書完成 ----

//--- 下面對《哈里波特》做一些修改。 ----
//--- 查詢找《哈里波特》----
theBook=(Element) selectSingleNode("/books/book[name='哈里波特']", root);
System.out.println("--- 查詢找《哈里波特》 ----");
output(theBook);
//--- 此時修改這本書的價格 -----
theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當於xpath的".//price"。
System.out.println("--- 此時修改這本書的價格 ----");
output(theBook);
//--- 另外還想加一個屬性id,值為B01 ----
theBook.setAttribute("id", "B01");
System.out.println("--- 另外還想加一個屬性id,值為B01 ----");
output(theBook);
//--- 對《哈里波特》修改完成。 ----

//--- 要用id屬性刪除《三國演義》這本書 ----
theBook=(Element) selectSingleNode("/books/book[@id='B02']", root);
System.out.println("--- 要用id屬性刪除《三國演義》這本書 ----");
output(theBook);
theBook.getParentNode().removeChild(theBook);
System.out.println("--- 刪除後的XML ----");
output(xmldoc);

//--- 再將所有價格低於10的書刪除 ----
NodeList someBooks=selectNodes("/books/book[price<10]", root);
System.out.println("--- 再將所有價格低於10的書刪除 ---");
System.out.println("--- 符合條件的書有"+someBooks.getLength()+"本。 ---");
for(int i=0;i<someBooks.getLength();i++) {
someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
}
output(xmldoc);

saveXml("Test1_Edited.xml", xmldoc);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void output(Node node) {//將node的XML字元串輸出到控制台
TransformerFactory transFactory=TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("encoding", "gb2312");
transformer.setOutputProperty("indent", "yes");

DOMSource source=new DOMSource();
source.setNode(node);
StreamResult result=new StreamResult();
result.setOutputStream(System.out);

transformer.transform(source, result);
} catch ( e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}

public static Node selectSingleNode(String express, Object source) {//查找節點,並返回第一個符合條件節點
Node result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(Node) xpath.evaluate(express, source, XPathConstants.NODE);
} catch (XPathExpressionException e) {
e.printStackTrace();
}

return result;
}

public static NodeList selectNodes(String express, Object source) {//查找節點,返回符合條件的節點集。
NodeList result=null;
XPathFactory xpathFactory=XPathFactory.newInstance();
XPath xpath=xpathFactory.newXPath();
try {
result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}

return result;
}

public static void saveXml(String fileName, Document doc) {//將Document輸出到文件
TransformerFactory transFactory=TransformerFactory.newInstance();
try {
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");

DOMSource source=new DOMSource();
source.setNode(doc);
StreamResult result=new StreamResult();
result.setOutputStream(new FileOutputStream(fileName));

transformer.transform(source, result);
} catch ( e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

❷ JAVA中如何用DOM4J將一個字元串解析成XML格式

用:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xmlStr.getBytes()));
試試。

❸ 如何用java生成一個XML文件,並且將該文件壓縮成ZIP格式後再寫到硬碟上

在你聲明ZipEntry的時候在name後加上.xml後綴就可以沖核了!!!
實例如下:

public static void main(String[] arg) throws Exception{

String xml;

/*
* 生成你的xml數據,存在String xml中。
*/散拿掘

ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("D://test.zip"));
//聲明ZipOutputStream,用來輸出zip文件。

ZipEntry entry = new ZipEntry("test.xml");
//聲明ZipEntry

zipOut.putNextEntry(entry);
//將entry加入到zipOut中。

DataOutputStream dataOs = new DataOutputStream(zipOut);
//利用DataOutputStream對ZipOutputStream進行包裝。敏宏
dataOs.writeUTF(gd);
//輸出zip文件。
dataOs.close();
}

運行後,在D盤里就有一個test.zip文件,里包含的就是一個test.xml文件了。

❹ 如何用java語言生成xml文件,並將它返回

實例:
holen.xml

<?xml version="1.0" encoding="UTF-8"?>

<books>

<!--This is a test for dom4j, holen, 2004.9.11-->

<book show="yes">

<title>Dom4j Tutorials</title>

</book>

<book show="yes">

<title>Lucene Studing</title>

</book>

<book show="no">

<title>Lucene in Action</title>

</book>

<owner>O'Reilly</owner>

</books>

建立一個XML文檔:

/**

* 建立一個XML文檔,文檔名由輸入屬性決定

* @param filename 需建立的文件名

* @return 返回操作結果, 0表失敗, 1表成功

*/

public int createXMLFile(String filename){

/** 返回操作結果, 0表失敗, 1表成功 */

int returnValue = 0;

/** 建立document對象 */

Document document = DocumentHelper.createDocument();

/** 建立XML文檔的根books */

Element booksElement = document.addElement("books");

/** 加入一行注釋 */

booksElement.addComment("This is a test for dom4j, holen, 2004.9.11");

/** 加入第一個book節點 */

Element bookElement = booksElement.addElement("book");

/** 加入show屬性內容 */

bookElement.addAttribute("show","yes");

/** 加入title節點 */

Element titleElement = bookElement.addElement("title");

/** 為title設置內容 */

titleElement.setText("Dom4j Tutorials");

/** 類似的完成後兩個book */

bookElement = booksElement.addElement("book");

bookElement.addAttribute("show","yes");

titleElement = bookElement.addElement("title");

titleElement.setText("Lucene Studing");

bookElement = booksElement.addElement("book");

bookElement.addAttribute("show","no");

titleElement = bookElement.addElement("title");

titleElement.setText("Lucene in Action");

/** 加入owner節點 */

Element ownerElement = booksElement.addElement("owner");

ownerElement.setText("O'Reilly");

try{

/** 將document中的內容寫入文件中 */

XMLWriter writer = new XMLWriter(new FileWriter(new File(filename)));

writer.write(document);

writer.close();

/** 執行成功,需返回1 */

returnValue = 1;

}catch(Exception ex){

ex.printStackTrace();

}

return returnValue;

}

說明:

Document document = DocumentHelper.createDocument();

通過這句定義一個XML文檔對象。

Element booksElement = document.addElement("books");

通過這句定義一個XML元素,這里添加的是根節點。

Element有幾個重要的方法:

l addComment:添加註釋

l addAttribute:添加屬性

l addElement:添加子元素

❺ 字元串在java類中怎麼轉換成xml文件

JXmlSerializable 是一個利用java反射,通過調用對象中所有以get(不區分大小寫)開頭的方法除去getClass方法,生成xml格式,希望與大家分享一下
下面是一個parent對象,包含兩個child對象 生成的xml如下

Child類

1package xmlTest;
2
3import java.io.FileNotFoundException;
4import java.io.IOException;
5import java.io.PrintWriter;
6import java.lang.reflect.InvocationTargetException;
7public class Child extends JXmlSerializable {
8
9 private String _name;
10 private String _sex;
11 private int age;
12
13 public void setAge(int num) {
14 age = num;
15 }
16
17 public int getAge() {
18 return age;
19 }
20
21 public void setName(String name) {
22 _name = name;
23 }
24
25 public void setSex(String sex) {
26 _sex = sex;
27 }
28
29 public String getName() {
30 return _name;
31 }
32
33 public String getSex() {
34 return _sex;
35 }
36
37}
38
Parent類 1package xmlTest;
2
3import java.io.PrintWriter;
4import java.lang.reflect.Array;
5import java.util.*;
6
7public class Parent extends JXmlSerializable {
8
9 private String _name;
10 private String _sex;
11 private LinkedList list = new LinkedList();
12 private Vector vec = new Vector();
13 int age;
14
15 public void setAge(int num) {
16 age = num;
17 }
18
19 public int getAge() {
20 return age;
21 }
22
23 public void setName(String name) {
24 _name = name;
25 }
26
27 public void setSex(String sex) {
28 _sex = sex;
29 }
30
31 public String getName() {
32 return _name;
33 }
34
35 public String getSex() {
36 return _sex;
37 }
38
39 public void addChild(Child child) {
40 list.add(child);
41 vec.add(child);
42 }
43
44 public Child[] getChild() {
45
46 Child[] aa = new Child[vec.size()];
47 // list.toArray(aa);
48 vec.toArray(aa);
49 return aa;
50 }
51
52 public static void main(String[] args) {
53 // TODO Auto-generated method stub
54 try {
55 Parent pat = new Parent();
56 pat.setName("jack");
57 pat.setSex("male");
58 Child child1 = new Child();
59 child1.setName("tom");
60 child1.setSex("male");
61 pat.addChild(child1);
62 Child child2 = new Child();
63 child2.setName("Marie");
64 child2.setSex("female");
65 pat.addChild(child2);
66 pat.getChild();
67 PrintWriter out = new PrintWriter("abc.xml");
68 pat.toXmlSerial(out,0);
69 out.flush();
70
71 } catch (Exception e) {
72 e.printStackTrace();
73 }
74
75 }
76}
類 JXmlSerializable
1package xmlTest;
2
3import java.lang.reflect.Method;
4import java.lang.reflect.InvocationTargetException;
5import java.lang.reflect.Array;
6import java.io.PrintWriter;
7import java.io.IOException;
8public class JXmlSerializable {
9
10 public void toXmlSerial(PrintWriter out, int num)
11 throws InvocationTargetException, IllegalAccessException,
12 IOException {
13 out.write("<?xml version="1.0"?> ");
14 String head = "";
15 for (int i = 0; i < num; i++) {
16 head += " ";
17 }
18 out.write(head + "<" + this.getClass().getName() + "> ");
19 Method[] methods = this.getClass().getMethods();
20 for (int i = 0; i < methods.length; i++) {
21 Class[] paras = methods[i].getParameterTypes();
22 String name = methods[i].getName();
23 if (paras == null || paras.length == 0) {
24 if ((name.substring(0, 3).toLowerCase().equals("get"))
25 && !name.equals("getClass")) {
26 Object obj = methods[i].invoke(this, null);
27 getMethodXmlSerial(out, obj, methods[i], num);
28 }
29 }
30 }
31
32 out.write(head + "</" + this.getClass().getName() + "> ");
33
34 }
35
36 private void getMethodXmlSerial(PrintWriter out, Object obj, Method method,
37 int num) throws InvocationTargetException, IllegalAccessException,
38 IOException {
39 if (obj == null)
40 return;
41 String head = "";
42 for (int i = 0; i <= num; i++) {
43 head += " ";
44 }
45 if (obj.getClass().isArray()) {
46 for (int i = 0; i < Array.getLength(obj); i++) {
47 Object childobj = Array.get(obj, i);
48 if (childobj instanceof JXmlSerializable) {
49 ((JXmlSerializable) childobj).toXmlSerial(out, num + 1);
50 } else {
51 getMethodXmlSerial(out, childobj, method, num);
52 }
53 }
54 } else {
55 out.write(head + " <" + method.getName().substring(3) + "> ");
56 out.write(obj.toString());
57 out.write(" </" + method.getName().substring(3) + "> ");
58 }
59
60 }
61}

編譯出來還可以,能夠達到我的理想。

編譯結果是

1<?xml version="1.0"?>
2<xmlTest.Parent>
3 <Name> jack </Name>
4 <Age> 0 </Age>
5 <Sex> male </Sex>
6<?xml version="1.0"?>
7 <xmlTest.Child>
8 <Name> tom </Name>
9 <Age> 0 </Age>
10 <Sex> male </Sex>
11 </xmlTest.Child>
12<?xml version="1.0"?>
13 <xmlTest.Child>
14 <Name> Marie </Name>
15 <Age> 0 </Age>
16 <Sex> female </Sex>
17 </xmlTest.Child>
18</xmlTest.Parent>
今天看了看java.beans包,發現了兩個好東西,XMLEncoder和XMLDecoder。發現自己以前把從XML存取對象真是太費力氣啦。做了小工具類,以後可以用用了。
1以下是引用片段:
2package com.imct.util;
3import java.beans.XMLDecoder;
4import java.beans.XMLEncoder;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.FileNotFoundException;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.util.ArrayList;
11import java.util.List;
12/** *//**
13 * <title>使用XML文件存取可序列化的對象的類</title>
14 * <description>提供保存和讀取的方法</description>
15 * @author 殷晉
16 * <right>清華大學汽車工程開發研究院@2005</right>
17 * @version 1.0
18 * 2005-8-5 16:44:49
19 */
20public class ObjectToXMLUtil
21{
22 /** *//**
23 * 把java的可序列化的對象(實現Serializable介面)序列化保存到XML文件裡面,如果想一次保存多個可序列化對象請用集合進行封裝
24 * 保存時將會用現在的對象原來的XML文件內容
25 * @param obj 要序列化的可序列化的對象
26 * @param fileName 帶完全的保存路徑的文件名
27 * @throws FileNotFoundException 指定位置的文件不存在
28 * @throws IOException 輸出時發生異常
29 * @throws Exception 其他運行時異常
30 */
31 public static void objectXmlEncoder(Object obj,String fileName)
32 throws FileNotFoundException,IOException,Exception
33 {
34 //創建輸出文件
35 File fo = new File(fileName);
36 //文件不存在,就創建該文件
37 if(!fo.exists())
38 {
39 //先創建文件的目錄
40 String path = fileName.substring(0,fileName.lastIndexOf('.'));
41 File pFile = new File(path);
42 pFile.mkdirs();
43 }
44 //創建文件輸出流
45 FileOutputStream fos = new FileOutputStream(fo);
46 //創建XML文件對象輸出類實例
47 XMLEncoder encoder = new XMLEncoder(fos);
48 //對象序列化輸出到XML文件
49 encoder.writeObject(obj);
50 encoder.flush();
51 //關閉序列化工具
52 encoder.close();
53 //關閉輸出流
54 fos.close();
55 }
56 /** *//**
57 * 讀取由objSource指定的XML文件中的序列化保存的對象,返回的結果經過了List封裝
58 * @param objSource 帶全部文件路徑的文件全名
59 * @return 由XML文件裡面保存的對象構成的List列表(可能是一個或者多個的序列化保存的對象)
60 * @throws FileNotFoundException 指定的對象讀取資源不存在
61 * @throws IOException 讀取發生錯誤
62 * @throws Exception 其他運行時異常發生
63 */
64 public static List objectXmlDecoder(String objSource)
65 throws FileNotFoundException,IOException,Exception
66 {
67 List objList = new ArrayList();
68 File fin = new File(objSource);
69 FileInputStream fis = new FileInputStream(fin);
70 XMLDecoder decoder = new XMLDecoder(fis);
71 Object obj = null;
72 try
73 {
74 while( (obj = decoder.readObject()) != null)
75 {
76 objList.add(obj);
77 }
78 }
79 catch (Exception e)
80 {
81 // TODO Auto-generated catch block
82 }
83 fis.close();
84 decoder.close();
85 return objList;
86 }
87}
88
89
90當然用Beans.instantiate也可以從文件中反序列化初對象
91
92

❻ 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相關的資料

熱點內容
python數字字元串轉數字 瀏覽:657
c程序員可以轉互聯網嗎 瀏覽:490
深圳交醫保用什麼app 瀏覽:461
pdf合並成一張 瀏覽:670
ie9文件夾怎麼查看ftp 瀏覽:62
唯品會python解密 瀏覽:852
安卓高拍儀有什麼用 瀏覽:241
同步盤用什麼app好 瀏覽:188
伺服器上下載是什麼意思 瀏覽:169
s6怎麼接電話加密 瀏覽:152
電腦的命令指令符打不開怎麼辦 瀏覽:535
可編程邏輯器件cpld開發板 瀏覽:888
加裝文件夾圖片 瀏覽:425
27歲程序員offer 瀏覽:619
中國建築史梁思成pdf 瀏覽:198
單片機雙核與單核區別 瀏覽:850
xss攻擊需要編譯的符號 瀏覽:140
南京單片機定址 瀏覽:897
自製西門子編程電纜 瀏覽:807
伺服器還叫什麼名 瀏覽:712