将Json格式的数据转换为XML
日期:2011-10-21 阅读:125 分类:Javascript
在开发中,有时候可能需要将Json数据转换为XML来表述,那么这里提供了Javascript和Java两个版本的转换,如下:
Javascript:
/**
* Change JSON object to XML string.
* The JSON object value must be a string,an array or object.
* If the value is an integer or a float value,you must add " or ' to the value.
* @author bitjjj
* @param isPretty If format xml
* @param separator Set line separator
* @example var util = new JsonToXml(true); var result = util.toXml(JSONObject);
* @return
*/
function JsonToXml(isPretty,separator){
this.result=[];
this.isPretty = !!isPretty;
this.separator = separator || "/r/n";
this.result.push("<?xml version=/"1.0/" encoding=/"utf-8/"?>");
if(this.isPretty){
//this.result.push(this.separator);
}
}
JsonToXml.prototype.spacialChars=["&","<",">","/"","'"];
JsonToXml.prototype.validChars:["&","<",">",""","'"],
JsonToXml.prototype.toString = function(){
return this.result.join("");
};
JsonToXml.prototype.replaceSpecialChar = function(s){
for(var i=0;i<this.spacialChars.length;i++){
s=s.replace(new RegExp(this.spacialChars[i],"g"),this.validChars[i]);
}
return s;
};
JsonToXml.prototype.appendText = function(s){
s = this.replaceSpecialChar(s);
this.result.push(s);
};
JsonToXml.prototype.appendFlagBegin = function(s){
this.result.push("<"+s+">");
};
JsonToXml.prototype.appendFlagEnd = function(s){
this.result.push("</"+s+">");
if(this.isPretty){
//this.result.push(this.separator);
}
};
JsonToXml.prototype.each = function(arr,cb){
for(var i=0;i<arr.length;i++){
cb(i,arr[i]);
}
};
/**
* format xml string to pretty string
* @param xml string
* @return pretty xml string
* @reference http://stackoverflow.com/questions/376373/pretty-printing-xml-with-javascript
*/
JsonToXml.prototype.formatXml = function (xml) {
var formatted = [];
var reg = /(>)(<)(//*)/g;
xml = xml.replace(reg, '$1'+this.separator+'$2$3');
var pad = 0,self = this;
this.each(xml.split(this.separator), function(index, node) {
var indent = 0;
if (node.match( /.+<///w[^>]*>$/ )) {
indent = 0;
}
else if (node.match( /^<///w/ )) {
if (pad != 0) {
pad -= 1;
}
}
else if (node.match( /^</w[^>]*[^//]>.*$/ )) {
indent = 1;
}
else {
indent = 0;
}
var padding = '';
for (var i = 0; i < pad; i++) {
padding += ' ';
}
formatted.push(padding + node + self.separator);
pad += indent;
});
return formatted.join("");
};
JsonToXml.prototype.toXml = function(json){
this._toXml(json);
if(this.isPretty){
return this.formatXml(this.toString());
}
return this.toString();
};
JsonToXml.prototype._toXml = function(json){
for(var tag in json){
//need to handle Array object specially
if(json[tag].constructor==Array){
for(var i=0;i<json[tag].length;i++){
this.appendFlagBegin(tag);
var item = json[tag][i];
if(item.constructor == Object){
this._toXml(item);
}
else if(item.constructor == Array){
var obj={};
obj[tag]=item;
this._toXml(obj);
}
else if(item.constructor == String){
this.appendText(item);
}
this.appendFlagEnd(tag);
}
}
else{
this.appendFlagBegin(tag);
if(json[tag].constructor==Object){
this._toXml(json[tag]);
}
else if(json[tag].constructor==String){
this.appendText(json[tag]);
}
this.appendFlagEnd(tag);
}
}
};
Java:
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Iterator;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONException;
import org.apache.wink.json4j.JSONObject;
/**
* Depend on json4j library
* @author bitjjj
*
*/
public class JsonToXML {
private static StringBuilder result = new StringBuilder(
"<?xml version=/"1.0/" encoding=/"utf-8/"?>");
private static String[] spacialChars = { "&", "<", ">", "/"", "'" };
private static String[] validChars = { "&", "<", ">", ""","'" };
/**
* @param args
* @throws IOException
* @throws JSONException
*/
public static void main(String[] args){
String jsonString = "{InterventionPlan:{"
+ "'name':'jeffco /" & <s<<cho>>ol>',"
+ "'item':[{title:'title1'},{title:'title2'},{title:'title3'}],"
+ "obj:{prop1:'val//'ue1',prop2:'value2'}}" + "}";
System.out.println(prettyFormat(toXml(jsonString),4));
}
/**
* For specail char there are bugs using this way to format xml string
* Don't suggest to use this method,just for debugging
* @param input
* @param indent
* @return
*/
public static String prettyFormat(String input, int indent) {
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String toXml(String jsonString){
try {
JSONObject jsonObject = new JSONObject(jsonString);
toXml(jsonObject);
} catch (Exception e) {
throw new RuntimeException(e);
}
return result.toString();
}
private static void toXml(JSONObject json) throws Exception {
Iterator<?> keyIter = json.keys();
while (keyIter.hasNext()) {
String key = (String) keyIter.next();
Object jsonValue = json.get(key);
if (jsonValue instanceof JSONArray) {
JSONArray arrayValue = (JSONArray) jsonValue;
for (int i = 0; i < arrayValue.length(); i++) {
appendFlagBegin(key);
Object arrItem = arrayValue.get(i);
if (arrItem instanceof JSONObject) {
toXml((JSONObject) arrItem);
} else if (arrItem instanceof JSONArray) {
String arrItemStr = "{" + key + ":"
+ ((JSONArray) arrItem).toString() + "}";
toXml(new JSONObject(arrItemStr));
} else {
appendText(arrItem.toString());
}
appendFlagEnd(key);
}
} else {
appendFlagBegin(key);
if (jsonValue instanceof JSONObject) {
toXml((JSONObject) jsonValue);
} else {
appendText(jsonValue.toString());
}
appendFlagEnd(key);
}
}
}
private static String replaceSpecialChar(String s) {
for (int i = 0; i < spacialChars.length; i++) {
s = s.replaceAll(spacialChars[i], validChars[i]);
}
return s;
}
private static void appendText(String s) {
result.append(replaceSpecialChar(s));
}
private static void appendFlagBegin(String str) {
result.append("<" + str + ">");
}
private static void appendFlagEnd(String str) {
result.append("</" + str + ">");
}
}
本页链接: http://www.scriptlover.com/static/1014-javascript-java-json-xml
标签: javascript java json xml
相关文章
- Javascript在chrome中辅助预订火车票的方法 2012-01-06
- 一款不错的日历控件 2008-07-31
- getElementsByClassName 2008-07-21
- Javascript常用函数归档 2008-12-01
- EasyWindow1.0 (更新版) 2008-06-25
- 正则和JSON解析引擎JSEL发布 2008-11-04
- JSON和浏览器安全 2009-05-11
- msxml3.dll错误'800c0005'系统错误: -2146697211 2012-01-04
- xmlhttp参考手册 2008-12-11
- xmlhttp的同步和异步操作 2009-01-31
- 解决microsoft.xmlhttp的缓存问题 2010-06-26
- XML DOM evaluate() 方法 2011-08-10
网友评论
#1: 2011-10-31 1:26:00 by iphone 5
I抎 must look at with you right here. Which can be not something I normally do! I just take satisfaction in reading through a submit that will make individuals believe. Moreover, many thanks for permitting me to comment!
#2: 2011-11-10 15:24:00 by Alyn
A good many vlaualebs you've given me.