English 中文(简体)
Javacast/jQuery:我如何在XML要素中获得一系列的所有属性?
原标题:JavaScript/jQuery: How do I get an array of all attributes in an XML element?
  • 时间:2009-11-10 03:42:35
  •  标签:

鉴于酒类中的XML成分类似:

$( <foo oy="vey" foo="bar" here="is" another="attribute" /> )

我是否能够利用 j或老大Script,获得含有XML要素所有特性名称的阵列? 我期望:

[ oy , foo , here , another ]
最佳回答

j 彩票功能是真的指使XML的,它可以穿透超文本,但并不真实。

如何使用浏览器XML教区:

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( <foo oy="vey" foo="bar" here="is" another="attribute" /> );
var foo = doc.childNodes[0];
for (var i = 0; i < foo.attributes.length; i++) {
  var attr = foo.attributes[i];
  alert(attr.name + " = " + attr.value); 
}

http://jsbin.com/ezawe“rel=“noretinger”>here。

问题回答

http://plugins.jquery.com/project/getAttributes”rel=“nofollow noreferer”> 这一金字节将有助于你做到这一点。

你们也可以使用老旧的 j子,如:

 var elt = document.getElementsByTagName( id ); 
 for (i=0;i<elt.attributes.length;i++){ 
     //elt.attributes[i].nodeName is what you want, .nodeValue for its value.
 }

A) Single <Foo> element

Do you need list of attributes of a single element?
... if so - do you really need an array?
Simple $( <foo ... /> ).get(0).attributes
...will give you NamedNodeMap (object) of attributes


B) All elements <Foo> in the whole (XML) document

@Soufiane Hassou s answer is showing approach but is missing the inner loop...

您是否需要在一份<全程>的XML文件中找到所有可能的内容(例如产品内容)的名称?

var yourElements = document.getElementsByTagName( Foo ); //get all <Foo> elements
var listOfAttributeNames = []; //prepare empty array for attribute names
var attributeNameBuffer; //buffer for current attribute name in loop

//Loop all elements
for(var i = 0; i < yourElements.length ; ++i){ 

   //Loop all attributes of a current element
   for( k = 0 ; k < yourElements[i].attributes.length ; ++k ){ 
       //Temporary store current attribute name
       attributeNameBuffer = yourElements[i].attributes[k].name;

       //First, 
       //test if the attribute name does not already exist in our array of names
       if( listOfAttributeNames.indexOf(attributeNameBuffer) == -1 )
         listOfAttributeNames.push( attributeNameBuffer ); //if not, add it
   }

} 
console.log(listOfAttributeNames); //display array of attributes in console




相关问题
热门标签