javastringtoxml
A. 如何用java封裝解析一個多層次的XML文件,急求大神幫助
下面提供了XML解析成實知判體類,以及實體類轉換成xml的方法。
public class SwitchXML {
private XStream xStream = new XStream();
private String xmlPath = "D:/data.xml";
// 1. obj -> xml(object類型轉換為xml類型)
public String printXML(User user) {
System.out.println("obj -> xml");
String xml = xStream.toXML(user);
System.out.println(xml);
return xml;
}
// 2. xml->obj(xml類型轉換為object類型,並列印)
public void printObj(String xml) {
System.out.println("xml -> obj");
User u = (User) xStream.fromXML(xml);
System.out.println(u.getUserName() + " " + u.getPassWord() + "搭隱改 " + u.getRegisteredTime());
}
// 3. 將object類型轉換為xml類型,並寫入XML文件(其他格式也可以,比如txt文件)
public void writerXML(User user) {
try {
FileOutputStream fs = new FileOutputStream(xmlPath);
xStream.toXML(user, fs);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 4. 讀取XML文件,載入進相應Object類型
public void readerXML() {
User user = new User();
FileInputStream fis = null;
try {
fis = new FileInputStream(xmlPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
xStream.fromXML(fis, user);
// 列印對象信息
System.out.println(user.toString());
// 列印對象的屬性值
System.out.println(user.getUserName() + "-" + user.getPassWord() + "-"
+ user.getRegisteredTime());
}
public static void main(String[] args) {
// 用戶名
String username = "admin";
/攜衫/ 密碼
String password = "admin";
// 注冊時間
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String registeredtime = format.format(now);
User user = new User(username, password, registeredtime);
SwitchXML switchXML = new SwitchXML();
// 1. object類型轉換為xml類型,在控制台列印
String xml = switchXML.printXML(user);
System.out.println("---------------------");
// 2. xml類型轉換為object類型,在控制台列印
switchXML.printObj(xml);
System.out.println("---------------------");
// 3. 將object類型轉換為xml類型,並寫入XML文件
switchXML.writerXML(user);
System.out.println("---------------------");
// 4. 讀取XML文件,載入進相應Object類型
switchXML.readerXML();
}
B. 用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();
}
}
}
C. xtream的工具使用
Xstream
需要的jar包
xpp3_min-1.1.4c.jar
xstream-1.3.1.jar
作用:
將xml字元串轉換為java對象,或者將java對象轉換為xml字元串
核心類:XStream xs = new XStream();
准備工作,先創建兩個java類:City和Province
@XStreamAlias("city")
public class City {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@XStreamAlias("province")
public class Province {
@XStreamAsAttribute()
private String name;
@XStreamImplicit(itemFieldName = "city")
private List citys;
public List getCitys() {
return citys;
}
public void setCitys(List citys) {
this.citys = citys;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第一:將java類轉換為xml字元串
XStream xs = new XStream();
String xml = xs.toXML(JavaBean);
列印的字元串會將類的包名作為xml的標簽,以及裡面的欄位都會變成標簽。
例如將City類變為xml字元串:
武漢
將Province變成xml字元串
湖北
武漢
所以為了能將列印的字元串變為我們所想要的格式,可以使用Xstream提供的註解進行格式化輸出
提供便捷註解
@XStreamAlias(別名) 對類和變數設置知慧別名
@XStreamAsAttribute 設置變數生成屬性
@XStreamOmitField 設置變數 不生成到XML
@XStreamImplicit(itemFieldName = 「hobbies」) 設置集合類型變數 別名
使註解生效
xStream.autodetectAnnotations(true);
第二:將xml字元串變為java對象
Object xs.fromXML(InputStream input); //將一個下買了指定的流變為java對象
Object xs.fromXML(String xml) /搭基答/將xml字元串變為java對象
Object xs.fromXML(InputStream input,Object root) ?
Object xs.fromXML(String xml,Object root) ?
注意:轉換的xml文檔必須與Java對象 的格式對應
例如:將下面xml字元串轉換為Java對象
武漢
則進行轉換時候:
XStream xs = new XStream();
Object o = xs.fromXML(in);
若對應的java格式一定是:
包名為:com.domain
類名為:City
裡面鋒物有一個成員屬性:name 提供setter/getter方法
若不是則可以使用別名:
a.為類設置別名
xs.alias("city", City.class);
b.為屬性添加別名
xstream.useAttributeFor(Blog.class,"author");
能不能通過註解將 xml轉換為制定的java對象 ?
能,手動用方法添加別名
D. JAVA以POST方式提交XML獲取返回值(返回格式為XML)
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setRequestMethod(「POST」);
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(xml);
outputStream.close();
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 釋放資源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
E. java如何將一段xml的字元串文件寫入到xml文件 然後再解析出來
用dom4j,獲畝中取指定的位元組 List rootList = root.selectNodes("RETURN_CD"); rootList.get(0);
獲旁讓取的就是成迅啟山功了哦
F. 如何把xml內容轉換為java格式
使用XStream完成 java 類與 XML 互換。
下面代碼實現了以下4種基本功能:
1. object類型轉換為xml類型,在控制台列印
2. xml類型轉換為object類型,在控制台列印
3. 將object類型轉換為xml類型,並寫入XML文件
4. 讀取XML文件,載入進相應Object類型
====================================================
1。載入 XStream 需要的jar包 xstream-1.4.2.jar
xpp3_min-1.1.4c.jar
xmlpull-1.1.3.1.jar
2。創建實體類User.java
package com.entity;
/**
* 實體類
*/
public class User {
private String userName;
private String passWord;
private String registeredTime;
public User() { }
public User(String userName, String passWord, String registeredTime) {
this.userName = userName;
this.passWord = passWord;
this.registeredTime = registeredTime;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getRegisteredTime() {
return registeredTime;
}
public void setRegisteredTime(String registeredTime) {
this.registeredTime = registeredTime;
}
}
3。編寫功能實現類
package com.switcher;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.entity.User;
import com.thoughtworks.xstream.XStream;
/**
*
* 使用 XStream不用任何映射就能實現多數 Java 對象的序列化。
* 在生成的 XML中對象名變成了元素名,類中的字元串組成了 XML中的元素內容。
* 使用 XStream 序列化的類不需要實現 Serializable 介面。
* XStream 是一種序列化工具而不是數據綁定工具
* 不能從XML 或者 XML Schema Definition (XSD) 文件生成類。
*/
public class SwitchXML {
/*
* XStream 不關心序列化/逆序列化的類的欄位的可見性。
* 序列化/逆序列化類的欄位不需要 getter 和 setter 方法。
* 序列化/逆序列化的類不需要有默認構造函數。
*/
private XStream xStream = new XStream();
private String xmlPath = "D:/userdata.xml";
// 1. obj -> xml(object類型轉換為xml類型)
public String printXML(User user) {
System.out.println("obj -> xml");
String xml = xStream.toXML(user);
System.out.println(xml);
return xml;
}
// 2. xml->obj(xml類型轉換為object類型,並列印)
public void printObj(String xml) {
System.out.println("xml -> obj");
User u = (User) xStream.fromXML(xml);
System.out.println(u.getUserName() + " " + u.getPassWord() + " " + u.getRegisteredTime());
}
// 3. 將object類型轉換為xml類型,並寫入XML文件(其他格式也可以,比如txt文件)
public void writerXML(User user) {
try {
FileOutputStream fs = new FileOutputStream(xmlPath);
xStream.toXML(user, fs);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 4. 讀取XML文件,載入進相應Object類型
public void readerXML() {
User user = new User();
FileInputStream fis = null;
try {
fis = new FileInputStream(xmlPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
xStream.fromXML(fis, user);
// 列印對象信息
System.out.println(user.toString());
// 列印對象的屬性值
System.out.println(user.getUserName() + "-" + user.getPassWord() + "-"
+ user.getRegisteredTime());
}
public static void main(String[] args) {
// 用戶名
String username = "admin";
// 密碼
String password = "admin";
// 注冊時間
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String registeredtime = format.format(now);
User user = new User(username, password, registeredtime);
SwitchXML switchXML = new SwitchXML();
// 1. object類型轉換為xml類型,在控制台列印
String xml = switchXML.printXML(user);
System.out.println("---------------------");
// 2. xml類型轉換為object類型,在控制台列印
switchXML.printObj(xml);
System.out.println("---------------------");
// 3. 將object類型轉換為xml類型,並寫入XML文件
switchXML.writerXML(user);
System.out.println("---------------------");
// 4. 讀取XML文件,載入進相應Object類型
switchXML.readerXML();
}
}
G. 求 Java序列化對象轉xml方法....
/**這里應用了JAVA的Marshall方法
*對象轉xml
*返回xml
*@paramtXLife
*@return
*/
publicstaticStringtXLiftToXML(com.TXLifetXLife){
Stringxml="";
try{
ByteArrayOutputStreamout=newByteArrayOutputStream();
JAXBContextjc=JAXBContext
.newInstance("com");//包的命名空間
Marshallerm=null;
synchronized(jc){
m=jc.createMarshaller();
}
m.setProperty(Marshaller.JAXB_ENCODING,"GBK");
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
m.marshal(tXLife,out);
xml=out.toString();//賦值
}catch(Exceptione){
xml=null;
}
returnxml;
}
H. 求助java讀取txt文件轉化為xml形式輸出
txt文件格式如下,採用的是一個服務端tomcat的log日誌
12345678[06/Mar/2013:18:43:55] 110.110.1.1 GET /rest/keyword/getallids/aid/3/os/android2.3.5/ver/1.0/ HTTP/1.1 200 210 1453 1.453 'Dalvik<img id="selectsearch-icon" alt="搜索" src="https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/iknow/qb/select-search.png">/1.4.0 (linux; U; Android 2.3.5; T550 Build/MocorDroid2.3.5)'[06/Mar/2013:18:43:55] 110.110.1.1 GET /rest/keyword/getallids/aid/3/os/android2.3.4/ver/1.0/ HTTP/1.1 200 210 1453 1.453 'Dalvik/1.4.0 (Linux; U; Android 2.3.4; LG-E730 Build/GRJ22)'[06/Mar/2013:18:43:55] 110.110.1.1 GET /rest/keyword/getallids/aid/3/os/android2.3.5/ver/1.0/ HTTP/1.1 200 210 1453 1.453 'Dalvik/1.4.0 (Linux; U; Android 2.3.5; <a class="-highlight"汪陪 href="https://www..com/s?wd=MI-ONE&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank">MI-ONE</a> <a class="-highlight" href="困兆蠢https://www..com/s?wd=Plus&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank">Plus</a> Build/GINGERBREAD)'[06/Mar/2013:18:43:55] 110.110.1.1 GET /rest/keyword/getallids/aid/3/os/android2.3.6/ver/1.0/ HTTP/1.1 200 210 1453 1.453 'Dalvik/1.4.0 (Linux; U; Android 2.3.6; GT-I9220 Build/GINGERBREAD)'[06/Mar/2013:18:43:55] 110.110.1.1 POST /rest/keyword/getallids/aid/3/os/android4.0.3/ver/1.0/ HTTP/1.1 200 210 1469 1.469 '猜亮Dalvik/1.6.0 (Linux; U; Android 4.0.3; <a class="-highlight" href="https://www..com/s?wd=HUAWEI&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank">HUAWEI</a> <a class="-highlight" href="https://www..com/s?wd=C8812&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank">C8812</a> Build/<a class="-highlight" href="https://www..com/s?wd=Huawei&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank">Huawei</a><a class="-highlight" href="https://www..com/s?wd=C8812&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank">C8812</a>)'[06/Mar/2013:18:43:55] 110.110.1.1 GET /rest/keyword/getallids/aid/3/os/android2.2.2/ver/1.0/ HTTP/1.1 200 210 1453 1.453 'Dalvik/1.2.0 (Linux; U; Android 2.2.2; <a class="-highlight" href="https://www..com/s?wd=HUAWEI&tn=44039180_cpr&fenlei=_5y9YIZ0lQzqlpA-" target="_blank">HUAWEI</a> T8300 Build/FRF91)'[06/Mar/2013:18:43:55] 110.110.1.1 GET /rest/keyword/getallids/aid/3/os/android2.3.6/ver/1.0/ HTTP/1.0 200 210 1484 1.484 'Dalvik/1.4.0 (Linux; U; Android 2.3.6; Mytel Build/GRK39F)'[06/Mar/2013:18:43:55] 110.110.1.1 POST /rest/keyword/getallids/aid/3/os/android4.1.1/ver/1.0/ HTTP/1.1 200 210 1406 1.406 'Dalvik/1.6.0 (Linux; U; Android 4.1.1; GT-N7100 Build/JRO03C)'轉換代碼如下
ge test;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Writer;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.XMLWriter;public class promble04 { @SuppressWarnings("resource") public static void txtToXML(String txtPath) throws IOException { File file = new File(txtPath); Document document = DocumentHelper.createDocument(); Element list = document.addElement("list"); BufferedReader br = new BufferedReader(new FileReader(file)); String line = br.readLine(); while(line!=null) { String temp[] = line.split(" "); Element log = list.addElement("log"); Element time = log.addElement("time"); Element ip = log.addElement("ip"); Element httpType = log.addElement("httpType"); Element url = log.addElement("url"); Element httplevel = log.addElement("httplevel"); Element linuxVersion = log.addElement("linuxVersion"); Element os = log.addElement("os"); Element AndroidVersion = log.addElement("AndroidVersion"); Element phoneType = log.addElement("phoneType"); for(int i = 0;i<temp.length;i++) { time.setText(temp[0]); ip.setText(temp[1]); httpType.setText(temp[2]); url.setText(temp[3]); httplevel.setText(temp[4]); linuxVersion.setText(temp[9]); os.setText(temp[10]); AndroidVersion.setText(temp[12]); phoneType.setText(temp[13]); } line = br.readLine(); } Writer filewriter = new FileWriter("D:\log\test.xml"); XMLWriter xmlWriter = new XMLWriter(filewriter); xmlWriter.write(document); xmlWriter.close(); } public static void main(String args[]) throws IOException { promble04.txtToXML("D:\log\test.txt"); }}轉換結果如下
<?xml version="1.0" encoding="UTF-8"?><list> <log> <time>[06/Mar/2013:18:43:55]</time> <ip>110.110.1.1</ip> <httpType>GET</httpType> <url>/rest/keyword/getallids/aid/3/os/android2.3.5/ver/1.0/</url> <httplevel>HTTP/1.1</httplevel> <linuxVersion>'Dalvik/1.4.0</linuxVersion> <os>(Linux;</os> <AndroidVersion>Android</AndroidVersion> <phoneType>2.3.5;</phoneType> </log> <log> <time>[06/Mar/2013:18:43:55]</time> <ip>110.110.1.1</ip> <httpType>GET</httpType> <url>/rest/keyword/getallids/aid/3/os/android2.3.4/ver/1.0/</url> <httplevel>HTTP/1.1</httplevel> <linuxVersion>'Dalvik/1.4.0</linuxVersion> <os>(Linux;</os> <AndroidVersion>Android</AndroidVersion> <phoneType>2.3.4;</phoneType> </log> <log> <time>[06/Mar/2013:18:43:55]</time> <ip>110.110.1.1</ip> <httpType>GET</httpType> <url>/rest/keyword/getallids/aid/3/os/android2.3.5/ver/1.0/</url> <httplevel>HTTP/1.1</httplevel> <linuxVersion>'Dalvik/1.4.0</linuxVersion> <os>(Linux;</os> <AndroidVersion>Android</AndroidVersion> <phoneType>2.3.5;</phoneType> </log> <log> <time>[06/Mar/2013:18:43:55]</time> <ip>110.110.1.1</ip> <httpType>GET</httpType> <url>/rest/keyword/getallids/aid/3/os/android2.3.6/ver/1.0/</url> <httplevel>HTTP/1.1</httplevel> <linuxVersion>'Dalvik/1.4.0</linuxVersion> <os>(Linux;</os> <AndroidVersion>Android</AndroidVersion> <phoneType>2.3.6;</phoneType> </log> <log> <time>[06/Mar/2013:18:43:55]</time> <ip>110.110.1.1</ip> <httpType>POST</httpType> <url>/rest/keyword/getallids/aid/3/os/android4.0.3/ver/1.0/</url> <httplevel>HTTP/1.1</httplevel> <linuxVersion>'Dalvik/1.6.0</linuxVersion> <os>(Linux;</os> <AndroidVersion>Android</AndroidVersion> <phoneType>4.0.3;</phoneType> </log> <log> <time>[06/Mar/2013:18:43:55]</time> <ip>110.110.1.1</ip> <httpType>GET</httpType> <url>/rest/keyword/getallids/aid/3/os/android2.2.2/ver/1.0/</url> <httplevel>HTTP/1.1</httplevel> <linuxVersion>'Dalvik/1.2.0</linuxVersion> <os>(Linux;</os> <AndroidVersion>Android</AndroidVersion> <phoneType>2.2.2;</phoneType> </log> <log> <time>[06/Mar/2013:18:43:55]</time> <ip>110.110.1.1</ip> <httpType>GET</httpType> <url>/rest/keyword/getallids/aid/3/os/android2.3.6/ver/1.0/</url> <httplevel>HTTP/1.0</httplevel> <linuxVersion>'Dalvik/1.4.0</linuxVersion> <os>(Linux;</os> <AndroidVersion>Android</AndroidVersion> <phoneType>2.3.6;</phoneType> </log> <log> <time>[06/Mar/2013:18:43:55]</time> <ip>110.110.1.1</ip> <httpType>POST</httpType> <url>/rest/keyword/getallids/aid/3/os/android4.1.1/ver/1.0/</url> <httplevel>HTTP/1.1</httplevel> <linuxVersion>'Dalvik/1.6.0</linuxVersion> <os>(Linux;</os> <AndroidVersion>Android</AndroidVersion> <phoneType>4.1.1;</phoneType> </log></list>
I. JAVA讀取本地TXT文件轉換為XML文件輸出
txt文件格式如下,採用的是一個服務端tomcat的log日誌
[06/Mar/2013:18:43:55]110.110.1.1GET/rest/keyword/getallids/aid/3/os/android2.3.5/ver/1.0/HTTP/1.120021014531.453'Dalvik/1.4.0(Linux;U;Android2.3.5;T550Build/MocorDroid2.3.5)'
[06/Mar/2013:18:43:55]110.110.1.1GET/rest/keyword/getallids/aid/3/os/android2.3.4/ver/1.0/HTTP/1.120021014531.453'Dalvik/1.4.0(Linux;U;Android2.3.4;LG-E730Build/GRJ22)'
[06/Mar/2013:18:43:55]110.110.1.1GET/rest/keyword/getallids/aid/3/os/android2.3.5/ver/1.0/HTTP/1.120021014531.453'Dalvik/1.4.0(Linux;U;Android2.3.5;MI-ONEPlusBuild/GINGERBREAD)'
[06/Mar/2013:18:43:55]110.110.1.1GET/rest/keyword/getallids/aid/3/os/android2.3.6/ver/1.0/HTTP/1.120021014531.453'Dalvik/1.4.0(Linux;U;Android2.3.6;GT-I9220Build/GINGERBREAD)'
[06/Mar/2013:18:43:55]110.110.1.1鉛信POST/rest/keyword/getallids/aid/3/os/android4.0.3/ver/1.0/HTTP/1.120021014691.469亮穗'Dalvik/1.6.0(Linux;U;Android4.0.3;HUAWEIC8812Build/HuaweiC8812)'
[06/Mar/2013:18:43:55]110.110.1.1GET/rest/keyword/getallids/aid/3/os/android2.2.2/ver/1.0/HTTP/1.120021014531.453'Dalvik/1.2.0(Linux;敬激卜U;Android2.2.2;HUAWEIT8300Build/FRF91)'
[06/Mar/2013:18:43:55]110.110.1.1GET/rest/keyword/getallids/aid/3/os/android2.3.6/ver/1.0/HTTP/1.020021014841.484'Dalvik/1.4.0(Linux;U;Android2.3.6;MytelBuild/GRK39F)'
[06/Mar/2013:18:43:55]110.110.1.1POST/rest/keyword/getallids/aid/3/os/android4.1.1/ver/1.0/HTTP/1.120021014061.406'Dalvik/1.6.0(Linux;U;Android4.1.1;GT-N7100Build/JRO03C)'
轉換代碼如下
packagetest;
importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileReader;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.io.Writer;
importorg.dom4j.Document;
importorg.dom4j.DocumentHelper;
importorg.dom4j.Element;
importorg.dom4j.io.XMLWriter;
publicclasspromble04{
@SuppressWarnings("resource")
publicstaticvoidtxtToXML(StringtxtPath)throwsIOException
{
Filefile=newFile(txtPath);
Documentdocument=DocumentHelper.createDocument();
Elementlist=document.addElement("list");
BufferedReaderbr=newBufferedReader(newFileReader(file));
Stringline=br.readLine();
while(line!=null)
{
Stringtemp[]=line.split("");
Elementlog=list.addElement("log");
Elementtime=log.addElement("time");
Elementip=log.addElement("ip");
ElementhttpType=log.addElement("httpType");
Elementurl=log.addElement("url");
Elementhttplevel=log.addElement("httplevel");
ElementlinuxVersion=log.addElement("linuxVersion");
Elementos=log.addElement("os");
ElementAndroidVersion=log.addElement("AndroidVersion");
ElementphoneType=log.addElement("phoneType");
for(inti=0;i<temp.length;i++)
{
time.setText(temp[0]);
ip.setText(temp[1]);
httpType.setText(temp[2]);
url.setText(temp[3]);
httplevel.setText(temp[4]);
linuxVersion.setText(temp[9]);
os.setText(temp[10]);
AndroidVersion.setText(temp[12]);
phoneType.setText(temp[13]);
}
line=br.readLine();
}
Writerfilewriter=newFileWriter("D:\log\test.xml");
XMLWriterxmlWriter=newXMLWriter(filewriter);
xmlWriter.write(document);
xmlWriter.close();
}
publicstaticvoidmain(Stringargs[])throwsIOException
{
promble04.txtToXML("D:\log\test.txt");
}
}
轉換結果如下
<?xmlversion="1.0"encoding="UTF-8"?>
<list>
<log>
<time>[06/Mar/2013:18:43:55]</time>
<ip>110.110.1.1</ip>
<httpType>GET</httpType>
<url>/rest/keyword/getallids/aid/3/os/android2.3.5/ver/1.0/</url>
<httplevel>HTTP/1.1</httplevel>
<linuxVersion>'Dalvik/1.4.0</linuxVersion>
<os>(Linux;</os>
<AndroidVersion>Android</AndroidVersion>
<phoneType>2.3.5;</phoneType>
</log>
<log>
<time>[06/Mar/2013:18:43:55]</time>
<ip>110.110.1.1</ip>
<httpType>GET</httpType>
<url>/rest/keyword/getallids/aid/3/os/android2.3.4/ver/1.0/</url>
<httplevel>HTTP/1.1</httplevel>
<linuxVersion>'Dalvik/1.4.0</linuxVersion>
<os>(Linux;</os>
<AndroidVersion>Android</AndroidVersion>
<phoneType>2.3.4;</phoneType>
</log>
<log>
<time>[06/Mar/2013:18:43:55]</time>
<ip>110.110.1.1</ip>
<httpType>GET</httpType>
<url>/rest/keyword/getallids/aid/3/os/android2.3.5/ver/1.0/</url>
<httplevel>HTTP/1.1</httplevel>
<linuxVersion>'Dalvik/1.4.0</linuxVersion>
<os>(Linux;</os>
<AndroidVersion>Android</AndroidVersion>
<phoneType>2.3.5;</phoneType>
</log>
<log>
<time>[06/Mar/2013:18:43:55]</time>
<ip>110.110.1.1</ip>
<httpType>GET</httpType>
<url>/rest/keyword/getallids/aid/3/os/android2.3.6/ver/1.0/</url>
<httplevel>HTTP/1.1</httplevel>
<linuxVersion>'Dalvik/1.4.0</linuxVersion>
<os>(Linux;</os>
<AndroidVersion>Android</AndroidVersion>
<phoneType>2.3.6;</phoneType>
</log>
<log>
<time>[06/Mar/2013:18:43:55]</time>
<ip>110.110.1.1</ip>
<httpType>POST</httpType>
<url>/rest/keyword/getallids/aid/3/os/android4.0.3/ver/1.0/</url>
<httplevel>HTTP/1.1</httplevel>
<linuxVersion>'Dalvik/1.6.0</linuxVersion>
<os>(Linux;</os>
<AndroidVersion>Android</AndroidVersion>
<phoneType>4.0.3;</phoneType>
</log>
<log>
<time>[06/Mar/2013:18:43:55]</time>
<ip>110.110.1.1</ip>
<httpType>GET</httpType>
<url>/rest/keyword/getallids/aid/3/os/android2.2.2/ver/1.0/</url>
<httplevel>HTTP/1.1</httplevel>
<linuxVersion>'Dalvik/1.2.0</linuxVersion>
<os>(Linux;</os>
<AndroidVersion>Android</AndroidVersion>
<phoneType>2.2.2;</phoneType>
</log>
<log>
<time>[06/Mar/2013:18:43:55]</time>
<ip>110.110.1.1</ip>
<httpType>GET</httpType>
<url>/rest/keyword/getallids/aid/3/os/android2.3.6/ver/1.0/</url>
<httplevel>HTTP/1.0</httplevel>
<linuxVersion>'Dalvik/1.4.0</linuxVersion>
<os>(Linux;</os>
<AndroidVersion>Android</AndroidVersion>
<phoneType>2.3.6;</phoneType>
</log>
<log>
<time>[06/Mar/2013:18:43:55]</time>
<ip>110.110.1.1</ip>
<httpType>POST</httpType>
<url>/rest/keyword/getallids/aid/3/os/android4.1.1/ver/1.0/</url>
<httplevel>HTTP/1.1</httplevel>
<linuxVersion>'Dalvik/1.6.0</linuxVersion>
<os>(Linux;</os>
<AndroidVersion>Android</AndroidVersion>
<phoneType>4.1.1;</phoneType>
</log>
</list>
J. 【高分求助】java 中 數組格式的 json 怎麼轉成 xml
首先樓主的json數據有問題。
下面代碼親測,可用,兩個文件放在同級目錄:
Test.java
publicclassTest{
publicstaticvoidmain(String[]args){
ConvertXMLtoJSON();
StringjStr="{"users":{"user":["
+"{"uid":"1","node_id":"2","children":[{"id":"43","value":"14"},{"id":"44","value":"15"}]},"
+"{"uid":"2","node_id":"2","children":[{"id":"45","value":"11"},{"id":"46","value":"11"},{"id":"47","value":"16"}]},"
+"{"uid":"3","node_id":"2","children":{"id":"48","value":"11"}}]}"
+"}";
System.out.println(jsontoXml(jStr));
}
publicstaticStringjsontoXml(Stringjson){
try{
XMLSerializerserializer=newXMLSerializer();
JSONjsonObject=JSONSerializer.toJSON(json);
returnserializer.write(jsonObject);
}catch(Exceptione){
e.printStackTrace();
}
returnnull;
}
(){
InputStreamis=Test.class.getResourceAsStream("sample.xml");
Stringxml;
try{
xml=IOUtils.toString(is);
System.out.println(xml);
XMLSerializerxmlSerializer=newXMLSerializer();
JSONjson=xmlSerializer.read(xml);
System.out.println(json.toString(1));
}catch(IOExceptione){
e.printStackTrace();
}
}
}
sample.xml
<?xmlversion="1.0"encoding="utf-8"?>
<o>
<usersclass="object">
<userclass="array">
<eclass="object">
<childrenclass="array">
<eclass="object">
<idtype="string">43</id>
埋蔽<valuetype="string">14</value>
</e>
<eclass="object">
<idtype="string">44</id>
<valuetype="string">15</value>
</e>
</children>
<node_idtype="string">2</node_id>
<uidtype="string">1</uid>
</e>
<eclass="object">
<childrenclass="array">
<eclass="object">
<idtype="string">45</id>
<valuetype="string">11</value>
</e>
<eclass="object">
<idtype="string">46</id>
<valuetype="string">11</value>
</e>
<eclass="object">
沒中<idtype="string">47</id>
<valuetype="string">16</value>
枯液山</e>
</children>
<node_idtype="string">2</node_id>
<uidtype="string">2</uid>
</e>
<eclass="object">
<childrenclass="object">
<idtype="string">48</id>
<valuetype="string">11</value>
</children>
<node_idtype="string">2</node_id>
<uidtype="string">3</uid>
</e>
</user>
</users>
</o>
jar包下載地址參考:http://hanyi366.iteye.com/blog/1162365