Js + XML operation xml file Login. xml is as follows.
The Code is as follows:
Now you need to operate on the content of this xml file.
First, we need to load this xml file. xml files are loaded in js through XMLDOM.
The Code is as follows:
// Load the xml document
LoadXML = function (xmlFile)
{
Var xmlDoc;
If (window. ActiveXObject)
{
XmlDoc = new ActiveXObject ('Microsoft. XMLDOM ');
XmlDoc. async = false;
XmlDoc. load (xmlFile );
}
Else if (document. implementation & document. implementation. createDocument)
{
XmlDoc = document. implementation. createDocument ('','', null );
XmlDoc. load (xmlFile );
}
Else
{
Return null;
}
Return xmlDoc;
}
The xml file object comes out. Next, I will operate on this document.
For example, if we need to get the attributes of the first node of the node Login/Weapon/W, we can proceed as follows.
The Code is as follows:
// First, judge the xml Object
CheckXMLDocObj = function (xmlFile)
{
Var xmlDoc = loadXML (xmlFile );
If (xmlDoc = null)
{
Alert ('your browser does not support reading xml files, so this page prohibits your operations. We recommend you use IE5.0 or above to solve this problem! ');
Window. location. href = '/Index. aspx ';
}
Return xmlDoc;
}
// Then obtain the attribute value of the first node of Login/Weapon/W.
Var xmlDoc = checkXMLDocObj ('/EBS/XML/Login. xml ');
Var v = xmlDoc. getElementsByTagName ('login/Weapon/W') [0]. childNodes. getAttribute ('text ')
However, the way I write in my program is like this. Of course, the way I write in the program has been applied to the actual application.
The Code is as follows:
InitializeSelect = function (oid, xPath)
{
Var xmlDoc = checkXMLDocObj ('/EBS/XML/Login. xml ');
Var n;
Var l;
Var e = $ (oid );
If (e! = Null)
{
N = xmlDoc. getElementsByTagName (xPath) [0]. childNodes;
L = n. length;
For (var I = 0; I {
Var option = document. createElement ('option ');
Option. value = n [I]. getAttribute ('value ');
Option. innerHTML = n [I]. getAttribute ('text ');
E. appendChild (option );
}
}
}
In the above access code, we use xmlDoc. getElementsByTagName (xPath.
You can also access it through xmldoc.doc umentElement. childNodes (1)... childNodes (0). getAttribute ('text.
Some common methods:
XmlDoc.doc umentElement. childNodes (0). nodeName, you can get the name of this node.
XmlDoc.doc umentElement. childNodes (0). nodeValue, you can get the value of this node. This value comes from the xml format like this: BSo we can get the value of B.
XmlDoc.doc umentElement. childNodes (0). hasChild, which can be used to determine whether a subnode exists.
In my experience, it is best to use the getElementsByTagName (xPath) method to access the node, because it can be used to locate the node directly through xPath, which will provide better performance.