js如何解析xml字符串

JavaScript030

js如何解析xml字符串,第1张

var xmlStr = '<root><people><name>张三</name><address>北京</address></people></root>'

var result = null

eval('result=['+$(xmlStr).find('people').map(function(){

return '{'+$('*',this).map(function(){

return $(this).attr('tagName') + ':"' + $(this).text() + '"'

}).get().join(',') + '}'

}).get().join('],[')+']')

alert(result)

//result是一个数组,如果有多个people节点,则为:[{name:"张三",address="北京"},{name:"李四",address="上海"}]

不好意思偏题了,以下是你要的结果:

var result = $(xmlStr).find('people').children().map(function(){

return $(this).attr('tagName')+'='+$(this).text()

}).get().join()

上面的都是jquery的写法:

javascript的话:

用COM操作:

object xmlDoc = new ActiveObject('msxml2')

xmlDoc.loadXml(xmlStr)

var pNode = xmlDoc.selectSignNode('people')

var result = ''

for(var node in pNode.selectNodes('*')){

result+=(result.length>0?',':'') + node.nodeName+'='+node.innerText

}

alert(reuslt)

或者用DOM操作:

<xml id='testXml' />

var result = ''

with(document.getElementById('testXml')){

innerHTML = xmlStr

for(var child in children){

result += ',' + child.tagName + '=' + child.innerText

}

if(result.length >0){

result = result.substring(1)

}

}

//JS现在有叫做Ajax的技术,已经很成熟了,这是底层Ajax的实现,仅供参考

//如果应用,轻量级的,可以考虑JQuery封装的Ajax,JQuery考虑了主流浏览器的兼容性

var xHRObject = false

if (window.XMLHttpRequest)//判断XMLHttpRequest,火狐等

{

xHRObject = new XMLHttpRequest()

}

else if (window.ActiveXObject)//判断ActiveXObject,即IE

{

xHRObject = new ActiveXObject("Microsoft.XMLHTTP")

}

function getData()

{

if ((xHRObject.readyState == 4) &&(xHRObject.status == 200))

{

//以下是对返回的XML进行解释处理

var serverResponse = xHRObject.responseXML

var header = serverResponse.getElementsByTagName("book")

var spantag = document.getElementById("cart")

spantag.innerHTML = ""

for (i=0i<header.lengthi++)

{

if (window.ActiveXObject)

{

spantag.innerHTML += " " +header[0].firstChild.text

spantag.innerHTML += " " + header[0].lastChild.text + " " + "<a href='#' onclick='AddRemoveItem(\"Remove\")'>Remove Item</a>"

}

else

{

spantag.innerHTML += " " +header[0].firstChild.textContent

spantag.innerHTML += " " + header[0].lastChild.textContent + " " + "<a href='#' onclick='AddRemoveItem(\"Remove\")'>Remove Item</a>"

}

}

}

}

function AddRemoveItem(action)

{

var book = document.getElementById("book").innerHTML

if(action=="Add")

{

xHRObject.open("GET", "ManageCart.aspx?action=" + action + "&book=" + encodeURIComponent(book) + "&value=" + Number(new Date), true)//此处可以改成指定的请求HTTP路径

}

else

{

xHRObject.open("GET", "ManageCart.aspx?action=" + action + "&book=" + encodeURIComponent(book) + "&value=" + Number(new Date), true)//此处可以改成指定的请求HTTP路径

}

xHRObject.onreadystatechange = getData//绑定事件函数

xHRObject.send(null)//异步发送

}