JS解析XML文件和XML字符串

JS解析XML文件

 

複製代碼
<script type='text/javascript'>
    loadXML 
= function(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;
    }
</script>
複製代碼

 

JS解析XML字符串

 

複製代碼
<script type='text/javascript'>
    loadXML 
= function(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;
    }
</script>
複製代碼

 

測試XML

 

複製代碼
<?xml version="1.0" encoding="utf-8" ?>
<DongFang>
  
<Company>
    
<cNname>1</cNname>
    
<cIP>1</cIP>
  
</Company>
  
<Company>
    
<cNname>2</cNname>
    
<cIP>2</cIP>
  
</Company>    
  
<Company>
    
<cNname>3</cNname>
    
<cIP>3</cIP>
  
</Company>
  
<Company>
    
<cNname>4</cNname>
    
<cIP>4</cIP>
  
</Company>
  
<Company>
    
<cNname>5</cNname>
    
<cIP>5</cIP>
  
</Company>
  
<Company>
    
<cNname>6</cNname>
    
<cIP>6</cIP>
  
</Company>
</DongFang>
複製代碼

 

 

使用方法

 var xmldoc=loadXML(text.xml)

 var elements = xmlDoc.getElementsByTagName("Company");

 for (var i = 0; i < elements.length; i++) {
                var name = elements[i].getElementsByTagName("cNname")[0].firstChild.nodeValue;
                var ip = elements[i].getElementsByTagName("cIP")[0].firstChild.nodeValue;               

var e = elements[i];

for(var j in e){

console.log(j+" : "+e[j]);

}

}


childElementCount  :  0
lastElementChild  :  null
firstElementChild  :  null
children  :  [object HTMLCollection]
nextElementSibling  :  null
previousElementSibling  :  null
onwebkitfullscreenerror  :  null
onwebkitfullscreenchange  :  null
onwheel  :  null
onselectstart  :  null
onsearch  :  null
onpaste  :  null
oncut  :  null
oncopy  :  null
onbeforepaste  :  null
onbeforecut  :  null
onbeforecopy  :  null
shadowRoot  :  null
dataset  :  [object DOMStringMap]
classList  :  
className  :  
outerHTML  :  <a>1234</a>
scrollHeight  :  0
scrollWidth  :  0
scrollTop  :  0
scrollLeft  :  0
clientHeight  :  0
clientWidth  :  0
clientTop  :  0
clientLeft  :  0
offsetParent  :  null
offsetHeight  :  0
offsetWidth  :  0
offsetTop  :  0
offsetLeft  :  0
localName  :  a
prefix  :  null
namespaceURI  :  null
style  :  null
attributes  :  [object NamedNodeMap]
tagName  :  a
parentElement  :  null
textContent  :  1234
nodeType  :  1
nodeValue  :  null
nodeName  :  a
id  :  
innerHTML  :  1234
getAttribute  :  function getAttribute() { [native code] }
setAttribute  :  function setAttribute() { [native code] }
removeAttribute  :  function removeAttribute() { [native code] }
getAttributeNode  :  function getAttributeNode() { [native code] }
setAttributeNode  :  function setAttributeNode() { [native code] }
removeAttributeNode  :  function removeAttributeNode() { [native code] }
getElementsByTagName  :  function getElementsByTagName() { [native code] }
hasAttributes  :  function hasAttributes() { [native code] }
getAttributeNS  :  function getAttributeNS() { [native code] }
setAttributeNS  :  function setAttributeNS() { [native code] }
removeAttributeNS  :  function removeAttributeNS() { [native code] }
getElementsByTagNameNS  :  function getElementsByTagNameNS() { [native code] }
getAttributeNodeNS  :  function getAttributeNodeNS() { [native code] }
setAttributeNodeNS  :  function setAttributeNodeNS() { [native code] }
hasAttribute  :  function hasAttribute() { [native code] }
hasAttributeNS  :  function hasAttributeNS() { [native code] }
matches  :  function matches() { [native code] }
closest  :  function closest() { [native code] }
focus  :  function focus() { [native code] }
blur  :  function blur() { [native code] }
scrollIntoView  :  function scrollIntoView() { [native code] }
scrollIntoViewIfNeeded  :  function scrollIntoViewIfNeeded() { [native code] }
getElementsByClassName  :  function getElementsByClassName() { [native code] }
insertAdjacentElement  :  function insertAdjacentElement() { [native code] }
insertAdjacentText  :  function insertAdjacentText() { [native code] }
insertAdjacentHTML  :  function insertAdjacentHTML() { [native code] }
webkitMatchesSelector  :  function webkitMatchesSelector() { [native code] }
createShadowRoot  :  function createShadowRoot() { [native code] }
getDestinationInsertionPoints  :  function getDestinationInsertionPoints() { [native code] }
getClientRects  :  function getClientRects() { [native code] }
getBoundingClientRect  :  function getBoundingClientRect() { [native code] }
requestPointerLock  :  function requestPointerLock() { [native code] }
animate  :  function animate() { [native code] }
remove  :  function remove() { [native code] }
webkitRequestFullScreen  :  function webkitRequestFullScreen() { [native code] }
webkitRequestFullscreen  :  function webkitRequestFullscreen() { [native code] }
querySelector  :  function querySelector() { [native code] }
querySelectorAll  :  function querySelectorAll() { [native code] }
parentNode  :  [object XMLDocument]
childNodes  :  [object NodeList]
firstChild  :  [object Text]
lastChild  :  [object Text]
previousSibling  :  null
nextSibling  :  null
ownerDocument  :  [object XMLDocument]
baseURI  :  
insertBefore  :  function insertBefore() { [native code] }
replaceChild  :  function replaceChild() { [native code] }
removeChild  :  function removeChild() { [native code] }
appendChild  :  function appendChild() { [native code] }
hasChildNodes  :  function hasChildNodes() { [native code] }
cloneNode  :  function cloneNode() { [native code] }
normalize  :  function normalize() { [native code] }
isSameNode  :  function isSameNode() { [native code] }
isEqualNode  :  function isEqualNode() { [native code] }
lookupPrefix  :  function lookupPrefix() { [native code] }
isDefaultNamespace  :  function isDefaultNamespace() { [native code] }
lookupNamespaceURI  :  function lookupNamespaceURI() { [native code] }
compareDocumentPosition  :  function compareDocumentPosition() { [native code] }
contains  :  function contains() { [native code] }
ELEMENT_NODE  :  1
ATTRIBUTE_NODE  :  2
TEXT_NODE  :  3
CDATA_SECTION_NODE  :  4
ENTITY_REFERENCE_NODE  :  5
ENTITY_NODE  :  6
PROCESSING_INSTRUCTION_NODE  :  7
COMMENT_NODE  :  8
DOCUMENT_NODE  :  9
DOCUMENT_TYPE_NODE  :  10
DOCUMENT_FRAGMENT_NODE  :  11
NOTATION_NODE  :  12
DOCUMENT_POSITION_DISCONNECTED  :  1
DOCUMENT_POSITION_PRECEDING  :  2
DOCUMENT_POSITION_FOLLOWING  :  4
DOCUMENT_POSITION_CONTAINS  :  8
DOCUMENT_POSITION_CONTAINED_BY  :  16
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC  :  32
addEventListener  :  function addEventListener() { [native code] }
removeEventListener  :  function removeEventListener() { [native code] }
dispatchEvent  :  function dispatchEvent() { [native code] }

發佈了22 篇原創文章 · 獲贊 29 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章