js解析xml,获取XMl标签属性值

js解析xml,获取XMl标签属性值

话不多说,直接上代码

  // 读取xml
      const loadXML = (xmlString) => {
        let xmlDoc = null;
        if (!window.DOMParser && window.ActiveXObject) {
          let 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) {
              console.log(e, "出现异常");
            }
          }
        } else if (
          window.DOMParser &&
          document.implementation &&
          document.implementation.createDocument
        ) {
          try {
            let domParser = new DOMParser();
            xmlDoc = domParser.parseFromString(xmlString, "text/xml");
          } catch (e) {
            console.log(e, "出现异常");
          }
        } else {
          return null;
        }
        return xmlDoc;
      };

//js解析xml
		function(){
			//加载xmlDoc
			var xmlDoc=loadXML(xml);
			//获取xml指定标签
			var entity=xmlDoc.getElementsByTagName("Entity")[0];
			//获取标签指定属性值
			var attr=entity.getAttribute("resourceName");
			alert(attr);
		}

你可能感兴趣的:(js,xml)