javascriptはxml解析xmlファイルを読みます.
5064 ワード
js xmlファイルを読みだします
jsはxml文字列を読みます.
htmlコードテスト:
function loadXML(xmlFile){
var xmlDoc=null;
//
// IE
if(!window.DOMParser && window.ActiveXObject){
var xmlDomVersions = ['MSXML.2.DOMDocument.6.0','MSXML.2.DOMDocument.3.0','Microsoft.XMLDOM'];
for(var i=0;i<xmlDomVersions.length;i++){
try{
xmlDoc = new ActiveXObject(xmlDomVersions[i]);
break;
}catch(e){
}
}
}
// Mozilla
else if(document.implementation && document.implementation.createDocument){
try{
/* document.implementation.createDocument('','',null);
* URI ;
* ;
* ( doctype)
*/
xmlDoc = document.implementation.createDocument('','',null);
}catch(e){
}
}
else{
return null;
}
if(xmlDoc!=null){
xmlDoc.async = false;
xmlDoc.load(xmlFile);
}
return xmlDoc;
}
jsはxml文字列を読みます.
function loadXMLStr(xmlString){
var xmlDoc=null;
//
// IE
if(!window.DOMParser && window.ActiveXObject){ //window.DOMParser ie
var xmlDomVersions = ['MSXML.2.DOMDocument.6.0','MSXML.2.DOMDocument.3.0','Microsoft.XMLDOM'];
for(var i=0;i<xmlDomVersions.length;i++){
try{
xmlDoc = new ActiveXObject(xmlDomVersions[i]);
xmlDoc.async = false;
xmlDoc.loadXML(xmlString); //loadXML xml
break;
}catch(e){
}
}
}
// Mozilla
else if(window.DOMParser && document.implementation && document.implementation.createDocument){
try{
/* DOMParser XML XML Document 。
* DOMParser, , parseFromString()
* parseFromString(text, contentType) text: XML contentType
* "text/xml" 、"application/xml" "application/xhtml+xml" 。 , "text/html"。
*/
domParser = new DOMParser();
xmlDoc = domParser.parseFromString(xmlString, 'text/xml');
}catch(e){
}
}
else{
return null;
}
return xmlDoc;
}
htmlコードテスト:
<script type="text/javascript">
window.onload = function(){
var text = document.getElementById('aaa').value;
var xmldoc=loadXMLStr(text);
var elements = xmldoc.getElementsByTagName("major");
for (var i = 0; i < elements.length; i++) {
var value = elements[i].getElementsByTagName("class")[0].firstChild.nodeValue;
alert(value);
}
}
</script>
<textarea id="aaa">
<IS>
<year time="2014">
<major name="Computer Science">
<class>1401</class>
<class>1402</class>
<class>1403</class>
<class>1404</class>
</major>
<major name="Communication Engineering">
<class>1405</class>
<class>1406</class>
<class>1407</class>
<class>1408</class>
</major>
</year>
<year time="2013">
<major name="Computer Science">
<class>1301</class>
<class>1302</class>
<class>1303</class>
<class>1304</class>
</major>
<major name="Communication Engineering">
<class>1305</class>
<class>1306</class>
<class>1307</class>
<class>1308</class>
</major>
</year>
</IS>
</textarea>