JavaScript XML操作パッケージ類
4421 ワード
function XMLObject()
{
this.isIE=true;
if (window.ActiveXObject){isIE=true;}else{isIE=false;}
var node_xml;
var xmlDoc;
if (isIE){
xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
}
else{
if (document.implementation && document.implementation.createDocument){
xmlDoc = document.implementation.createDocument("","",null);
}
}
xmlDoc.async = false;
xmlDoc.resolveExternals = false;
xmlDoc.validateOnParse = false;
xmlDoc.preserveWhiteSpace = true;
// XML (XML )
this.LoadXMLForString=function(XMLStr)
{
if(isIE)
{
xmlDoc.loadXML(XMLStr);
}
else
{
var oParser = new DOMParser();
xmlDoc = oParser.parseFromString(XMLStr,"text/xml");
}
}
// XML ( )
this.getXMLForURL=function(url)
{
//xmlDoc.load(url);
if (isIE){
xmlDoc.load(url);
}
else
{
xmlDoc = getXML(url).responseXML;
}
}
//
this.getXMLArray=function (name) {
var keys = name.split('.');
var node = xmlDoc.documentElement; //
var rtn = new Array();
var n = 0;
for(var i=0; ivar childs = node.childNodes; //
var key = keys[i];
for(var k=0; kvar child = childs[k];
if(child.nodeName == key) { //
if(i == keys.length-1) {
rtn[n] = child;
n++;
} else {
node = child;
break;
}
}
}
}
node_xml=rtn;
return rtn;
}
//
this.getNodeValue=function(name)
{
return this.getValue(xmlDoc,name);
}
//
this.getValue=function(node, name)
{
var keys = name.split('.');
for(var i=0; i{
var childs = node.childNodes; //
var key = keys[i];
for(var k=0; k{
var child = childs[k];
if(child.nodeName == key)
{ //
if(child.childNodes.length == 1)
{
// ,
if(!window.ActiveXObject)
{
return childs[k].textContent;
}
else
{
return childs[k].text
}
}
else
{
// ,
node = child;
break;
}
}
}
}
return "";
}
function GetXMLHTTP()
{
var xmlhttp;
if (window.ActiveXObject){
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}
catch (e){xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
}else if (window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest();}
return xmlhttp;
}
function getXML(url){
var xmlHttp=GetXMLHTTP();
if (xmlHttp!=null){
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
}else{
alert("Your browser does not support XMLHTTP.11");
return false;
}
return xmlHttp;
}
}
呼び出し方法DEMO
var strXML=" 27 26 25 ";
var XMLObj=new XMLObject();
XMLObj.LoadXMLForString(strXML)
//XMLObj.getXMLForURL("test.xml");
var list = XMLObj.getXMLArray( 'user');//
document.write(XMLObj.getNodeValue('ekuy.user.name.cnname'));//
//
for(var i=0; ivar obj = list[i];
document.write(XMLObj.getValue(obj, 'name.cnname'));
document.write(XMLObj.getValue(obj, 'age'));
document.write('
');
}
ほほほと書いたのはあまりよくないです.みんなが笑うのはとても簡単な機能です.