JavaScript/jQuery: How do I get an array of all attributes in an XML element?

后端 未结 3 925
甜味超标
甜味超标 2021-01-27 00:59

Given an XML element in jQuery like so:

$(\'\')

Can I use either jQuery o

3条回答
  •  被撕碎了的回忆
    2021-01-27 01:39

    The jQuery function isn't really meant to parse XML, it can parse HTML, but it's not really the same.

    What about using the browser's XML parser:

    function parseXML(text) {
      var parser, xmlDoc;
    
      if (window.DOMParser) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(text,"text/xml");
      } else {  // IE
        xmlDoc=  new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(text); 
      }
      return xmlDoc;
    }
    
    // Demo
    var doc = parseXML('');
    var foo = doc.childNodes[0];
    for (var i = 0; i < foo.attributes.length; i++) {
      var attr = foo.attributes[i];
      alert(attr.name + " = " + attr.value); 
    }
    

    Run the above code here.

提交回复
热议问题