通用的method
<script type="text/javascript"> //for chrome, attach method to XMLDocument if (!window.ActiveXObject) { XMLDocument.prototype.selectSingleNode = Element.prototype.selectSingleNode = function (xpath) { var x = this.selectNodes(xpath) ) return null; ]; } XMLDocument.prototype.selectNodes = Element.prototype.selectNodes = function (xpath) { var xpe = new XPathEvaluator(); var nsResolver = xpe.createNSResolver(this.ownerDocument == null ? this.documentElement : this.ownerDocument.documentElement); , null); var found = []; var res; while (res = result.iterateNext()) found.push(res); return found; } } function GetXMLDocument(xml) { if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) { var xmlDoc = new ActiveXObject('Microsoft.XMLDOM'); xmlDoc.async = false; xmlDoc.loadXML(xml); return xmlDoc; } else if (typeof window.DOMParser != "undefined") { return (new window.DOMParser()).parseFromString(xml, "text/xml"); } else { return null; } } // get xml node text function GetXMLNodeText(xmlNode) { if (xmlNode == null) return ""; var rt; if (window.ActiveXObject) // IE { rt = xmlNode.text; } else { // FireFox, Chrome, ... rt = xmlNode.textContent; } if (rt == null) rt = xmlNode.nodeValue; // XML DOM return rt; } </script>
Parse XML method
调用以上方法来解析“/NewDataSet/Table”型XML.
Example : <NewDataSet><Table><ID>1</ID><Name>test user 1</Name></Table><Table><ID>2</ID><Name>test user 2</Name></Table></NewDataSet>
function SelectorOption(id, name) { this.ID = id; this.Name = name; } function ParseDataSetXML(xml) { var options = []; var xmlDoc = GetXMLDocument(xml); if (xmlDoc) { var items = xmlDoc.selectNodes("/NewDataSet/Table"); ; j < items.length; j++) { var id = GetXMLNodeText(items[j].selectSingleNode("ID")); var name = GetXMLNodeText(items[j].selectSingleNode("Name")); options.push(new SelectorOption(id, name)); } } return options; }
实际应用中可通过调用function ParseDataSetXML来解析“/NewDataSet/Table”型XML 获得一个数组,attribute ID 对应节点“ID”, attribute Name 对应节点“Name”
function ReleaseXML() { var insertXML = document.getElementById("txt").value; var items = ParseDataSetXML(insertXML); ; j < items.length; j++) { document.getElementById("lbSelected").options.add(new Option(items[j].Name, items[j].ID)); } }