用javascript读xml的例子

2008-02-23 09:23:12来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

1.XML文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<zip>
<city>
mycity</city>
<state>mystate</state>
</zip>

2.读此xml的JavaScript例子:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script language="Javascript" type="text/javascript">

var url = "NewFile.xml";
String.prototype.Trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); }

var xmlDoc;

var moz = (typeof document.implementation != 'undefined')
&& (typeof document.implementation.createDocument != 'undefined');
var ie = (typeof window.ActiveXObject != 'undefined');

function importXML(file) {

if (moz) {
xmlDoc = document.implementation.createDocument("", "doc", null);

} else if (ie) {
xmlDoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
xmlDoc.async = false;
while(xmlDoc.readyState != 4) {};
}

xmlDoc.load(file);
}
importXML(url);

function updateCityState(){
if (moz) {
var zip = xmlDoc.getElementsByTagName("zip")[0];
var city;
var _city = zip.getElementsByTagName("city")[0].firstChild.nodeValue;
if (_city) city = _city.Trim();

var state;
var _state=zip.getElementsByTagName("state")[0].firstChild.nodeValue;
if(_state) state = _state.Trim();

document.getElementById('city').value = city;
document.getElementById('state').value = state;

} else if (ie) {
var city;
var _city = xmlDoc.selectSingleNode("/zip/city");
if (_city) city = _city.text;
var state;
var _state=xmlDoc.selectSingleNode("/zip/state");
if(_state) state = _state.text;
document.getElementById('city').value = city;
document.getElementById('state').value = state;
}
}
</script>
</head>
<body>
<form action="post">

<p>
ZIP code:
<input type="text" size="5" name="zip" id="zip" onblur="updateCityState();" />

</p>
City:
<input type="text" name="city" id="city" />

State:
<input type="text" size="2" name="state" id="state" />

</form>
</body>
</html>



上一篇: java模式设计全接触
下一篇: hibernate、Spring、Struts编程宝典

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:j2me 菜单设计方案1

下一篇:java模式设计全接触