当前位置:首页 » 编程语言 » javastringtoxml

javastringtoxml

发布时间: 2023-03-16 03:07:15

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

热点内容
动态规划01背包算法 发布:2024-11-05 22:17:40 浏览:849
nasm编译器如何安装 发布:2024-11-05 22:01:13 浏览:180
登录密码在微信的哪里 发布:2024-11-05 22:00:29 浏览:739
c防止反编译工具 发布:2024-11-05 21:56:14 浏览:247
安卓虚拟机怎么用 发布:2024-11-05 21:52:48 浏览:343
php时间搜索 发布:2024-11-05 20:58:36 浏览:478
燕山大学编译原理期末考试题 发布:2024-11-05 20:13:54 浏览:527
华为电脑出现临时服务器 发布:2024-11-05 20:05:08 浏览:408
斗战神免费挖矿脚本 发布:2024-11-05 19:53:25 浏览:665
网吧服务器分别是什么 发布:2024-11-05 19:45:32 浏览:392