js 如何读取xml文档内容

JavaScript014

js 如何读取xml文档内容,第1张

请把下面的代码保存为 readxml.html

<html>

<head>

<script type="text/javascript">

var xmlhttp

function loadXMLDoc(url)

{

xmlhttp=null

if (window.XMLHttpRequest)

  {// code for IE7, Firefox, Opera, etc.

  xmlhttp=new XMLHttpRequest()

  }

else if (window.ActiveXObject)

  {// code for IE6, IE5

  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

  }

if (xmlhttp!=null)

  {

  xmlhttp.onreadystatechange=state_Change

  xmlhttp.open("GET",url,true)

  xmlhttp.send(null)

  }

else

  {

  alert("Your browser does not support XMLHTTP.")

  }

}

function state_Change()

{

if (xmlhttp.readyState==4)

  {// 4 = "loaded"

  if (xmlhttp.status==200)

    {// 200 = "OK"

    document.getElementById('A1').innerHTML=xmlhttp.status

    document.getElementById('A2').innerHTML=xmlhttp.statusText

    

    document.getElementById('A3').innerHTML=xmlhttp.responseText

    }

  else

    {

    alert("Problem retrieving XML data:" + xmlhttp.statusText)

    }

  }

}

</script>

</head>

<body>

<h2>Using the HttpRequest Object</h2>

<p><b>Status:</b>

<span id="A1"></span>

</p>

<p><b>Status text:</b>

<span id="A2"></span>

</p>

<p><b>Response:</b>

<br /><span id="A3"></span>

</p>

<button onclick="loadXMLDoc('note.xml')">Get XML</button>

</body>

</html>

请把下面的文件保存未  note.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<note>

<to>George</to>

<from>John</from>

<heading>Reminder</heading>

<body>Don't forget the meeting!</body>

</note>

可以修改,我对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")