[英]JavaScript/jQuery: How do I get an array of all attributes in an XML element?
Given an XML element in jQuery like so: 给定jQuery中的XML元素,如下所示:
$('<foo oy="vey" foo="bar" here="is" another="attribute" />')
Can I use either jQuery or plain old JavaScript to get an array containing the names of all the attributes in an XML element? 我可以使用jQuery还是普通的旧JavaScript来获取一个包含XML元素中所有属性名称的数组? I would expect this: 我希望这样:
['oy','foo','here','another']
The jQuery function isn't really meant to parse XML, it can parse HTML, but it's not really the same. jQuery函数并不是真正要解析XML,它可以解析HTML,但实际上并不相同。
What about using the browser's XML parser: 如何使用浏览器的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);
}
This plugin will help you do that. 这个插件将帮助您做到这一点。
You can also do it using plain old javascript using something like that : 您也可以使用普通的旧JavaScript来实现,例如:
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.
}
<Foo>
element A)单个<Foo>
元素 Do you need list of attributes of a single element? 您是否需要单个元素的属性列表?
... if so - do you really need an array ? ...如果是这样-您真的需要一个数组吗?
Simple $('<foo ... />').get(0).attributes
简单的$('<foo ... />').get(0).attributes
...will give you NamedNodeMap (object) of attributes ...将为您提供NamedNodeMap(对象)的属性
<Foo>
in the whole (XML) document B)整个(XML)文档中的所有元素<Foo>
@Soufiane Hassou 's answer is showing approach but is missing the inner loop... @Soufiane Hassou的答案正在显示方法,但缺少内部循环...
Do you need to fetch all possible attribute names of an element (eg Product element) inside a whole XML document ? 您是否需要获取整个XML文档中某个元素(例如Product元素)的所有可能的属性名称?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.