日期:2014-05-16 浏览次数:20326 次
<script>
//XML 转 对象
var pXml = 0;
function getObj(xml,preTag)
{
var left = -1,right = -1;
var tag = "",content = "";
var obj = new Object();
while (pXml < xml.length)
{
left = xml.indexOf("<",pXml);
right = xml.indexOf(">",pXml);
if ((left | right != -1) && (left < right))
{
tag = xml.substring(left + 1,right);
if (tag[0] == "/")
{
if (tag != "/" + preTag)
{
//匹配错误
pXml = right + 1;
return;
}
if (obj.length)
{
pXml = right + 1;
return obj;
}
content = xml.substring(pXml,left);
pXml = right + 1;
return content;
}else
{
pXml = right + 1;
obj.length = ++obj.length || 1;
obj[tag] = getObj(xml,tag);
}
}else
{
break;
}
}
return obj;
}
function xmlToObj(xml)
{
pXml = 0;
return getObj(xml.substring(xml.indexOf(">") + 1,xml.lastIndexOf("<")));
}
//对象 转 XML
function getXml(obj)
{
var xml = "";
for (var attr in obj)
{
if (obj[attr] instanceof Object)
{
xml += "<" + attr + ">";
xml += getXml(obj[attr]);
xml += "</" + attr + ">";
}else
{
xml += "<" + attr + ">";
xml += obj[attr];
xml += "</" + attr + ">";
}
}
return xml;
}
function objToXml(obj)
{
return "<root>" + getXml(obj) + "</root>";
}
//测试数据
var obj1 = {
"First" : "Something",
"Second" : {
"First" : "Something more",
"Data" : "Some data"
},
"Third" : "Balabala"
};
//正常情况
var xml = objToXml(obj1)