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>