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] }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用JavaScript内置的XML解析器DOMParser来解析XML文件XML格式字符串。下面是一个示例代码: ```javascript // 定义一个XML格式的字符串 var xmlString = '<root><person><name>张三</name><age>18</age></person></root>'; // 创建一个DOMParser对象 var parser = new DOMParser(); // 解析XML字符串 var xmlDoc = parser.parseFromString(xmlString, 'text/xml'); // 获取XML文档中的元素 var name = xmlDoc.getElementsByTagName('name')[0].childNodes[0].nodeValue; var age = xmlDoc.getElementsByTagName('age')[0].childNodes[0].nodeValue; // 打印结果 console.log('name:', name); console.log('age:', age); ``` 在上面的代码中,我们首先定义了一个XML格式的字符串,然后创建了一个DOMParser对象,使用parseFromString方法来解析XML字符串,最后从解析后的文档中获取元素并打印结果。 如果要解析XML文件,可以使用XMLHttpRequest对象来获取XML文件内容,然后再使用DOMParser解析。具体代码请参考下面的示例: ```javascript // 创建XMLHttpRequest对象 var xhr = new XMLHttpRequest(); // 发送GET请求获取XML文件内容 xhr.open('GET', 'example.xml', true); xhr.send(); // 监听XML文件加载完成事件 xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { // 获取XML文件内容 var xmlString = xhr.responseText; // 创建DOMParser对象 var parser = new DOMParser(); // 解析XML字符串 var xmlDoc = parser.parseFromString(xmlString, 'text/xml'); // 获取XML文档中的元素 var name = xmlDoc.getElementsByTagName('name')[0].childNodes[0].nodeValue; var age = xmlDoc.getElementsByTagName('age')[0].childNodes[0].nodeValue; // 打印结果 console.log('name:', name); console.log('age:', age); } }; ``` 在上面的代码中,我们创建了一个XMLHttpRequest对象,使用GET请求获取XML文件内容,然后使用DOMParser解析XML字符串,最后从解析后的文档中获取元素并打印结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值