js读取XML文件

JavaScript015

js读取XML文件,第1张

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari

        xmlhttp = new XMLHttpRequest()

    }

    else {// code for IE6, IE5

        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")

    }

    xmlhttp.open("GET", "note.xml", false)

    xmlhttp.send()

    xmlDoc = xmlhttp.responseXML

    document.getElementById("to").innerHTML =

    xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue

    document.getElementById("from").innerHTML =

    xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue

    document.getElementById("message").innerHTML =

    xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue

可以修改,我对JS并不是非常熟悉,给你一段代码参考一下。<script>

var xmldom

function test()

{

xmldom = new ActiveXObject("Msxml2.DOMDocument")

xmldom.async = false

xmldom = document.all.mxh.XMLDocument

}

function test2()

{

var xmldom = new ActiveXObject("Msxml2.DOMDocument")

xmldom.async = false

xmldom = document.all.mxh.XMLDocument

node = xmldom.selectSingleNode("//nodeB")

node2 = xmldom.createElement("nodeB")

node2.text=parseInt(node.text)+1

xmldom.documentElement.replaceChild(node2,node)

node = xmldom.selectSingleNode("//nodeB")

alert(node.text)

alert(xmldom.xml)

}

function test3()

{

document.f.xmldata.value= document.all.mxh.XMLDocument.xml

alert(document.f.xmldata.value)

document.f.submit()

}

</script>

<body>

<XML id=mxh>

<root>

<nodeA>nodeA</nodeA>

<nodeB>30</nodeB>

</root>

</XML>

<form name=f action="xx.asp">

<input name=xmldata type=hidden>

<input onclick="test()" type="button" value=old>

<input onclick="test2()" type="button" value=请多点几次>

<input onclick="test3()" type="button" value=保存>

</form>

保存,调用 xmldom.save("xxx.xml")

最近在处理一个前端功能的时候,遇到了一个问题,原本的系统是使用的xml来存储数据的,而在新的系统上,想要转换为json对象存储,于是就考虑到直接将xml对象转换为json对象。

目前为止,通用的转换方式我还没有找到,只有根据已知的xml对象结构来使用for循环不断地赋值。

var

xml

=

······//获取xml对象

var

objList

=

[]

for(var

i

=

0i<xml.childNodes.lengthi++){

var

obj

=

{}

obj.attribute1

=

xml.getAttribute("attribute1")//获取节点属性

obj.attribute2

=

xml.getAttribute("attribute2")

obj.children

=

[]

for(var

x=0x<xml.childNodes[i].childNodes.lengthx++){

var

element

=

xml.childNodes[i].childNodes[x]

var

child

=

{}

child.attribute1

=

element.getAttribute("attribute1")

child.attribute2

=

element.getAttribute("attribute2")

obj.children.push(child)

}

objList.push(obj)

}

for循环可以继续嵌套下去,每一个新的json对象的属性都可以自定义,但是在getAttribute()方法中一定要填写自己所需要的存在的属性。

这样的方法看起来比较蠢,暂时先这样用吧,等到我想到了更好的方法之后在考虑替换。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。