我想迭代元素属性值并获得以下值:
1.电子邮件
2.部门
元素属性值如下所示:
<div id="divEntityData">
<div data="
<ArrayOfDictionaryEntry xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DictionaryEntry>
<Key xsi:type="xsd:string">Email</Key>
<Value xsi:type="xsd:string">abc@gmail.com</Value>
</DictionaryEntry>
<DictionaryEntry>
<Key xsi:type="xsd:string">Department</Key>
<Value xsi:type="xsd:string">IT</Value>
</DictionaryEntry>
<DictionaryEntry>
<Key xsi:type="xsd:string">AccountName</Key>
<Value xsi:type="xsd:string">abc</Value>
</DictionaryEntry>
<DictionaryEntry>
<Key xsi:type="xsd:string">PrincipalType</Key>
<Value xsi:type="xsd:string">User</Value>
</DictionaryEntry>
</ArrayOfDictionaryEntry>
">
</div>
</div>
到目前为止,我试过这样但没有得到正确的输出:
$(document).ready(function(){
var d = $("#divEntityData").find("div").attr("data");
//console.log();
for (var i=0; i<$(d).length; i++) {
console.log($(d)[i]);
}
});
答案 0 :(得分:6)
您需要进行XML DOM解析。
var txt = $("#divEntityData").find("div").attr("data");
var parser;
var xmlDoc;
if (window.DOMParser) {
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
} else { // Internet Explorer
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
现在,您可以对xmlDoc执行操作以获取数据。
例如
xmlDoc.getElementsByTagName("DictionaryEntry")[0].childNodes[0].nodeValue // Gives you Email
xmlDoc.getElementsByTagName("DictionaryEntry")[0].childNodes[1].nodeValue // Gives you abc@gmail.com
答案 1 :(得分:1)
更改jquery会提供一些结果:
$(document).ready(function(){
var d = $("ArrayOfDictionaryEntry").find("DictionaryEntry");
d.each(function(){
var key=$(this).find('Key').text();
var val=$(this).find('Value').text();
console.log(key+' '+val);
});
for (var i=0; i<$(d).length; i++) {
console.log($(d)[i]);
}
});
答案 2 :(得分:1)
var xml = $.parseXML( $('#divEntityData > div[data-xml]').data('xml') );
var xObj = {};
$(xml).find('DictionaryEntry').each(function(i,v) {
xObj[ $(v).find('Key').text() ] = $(v).find('Value').text();
});
console.log( xObj );
console.log( xObj.Department );
console.log( xObj.Email );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divEntityData">
<div data-xml='
<ArrayOfDictionaryEntry xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DictionaryEntry>
<Key xsi:type="xsd:string">Email</Key>
<Value xsi:type="xsd:string">abc@gmail.com</Value>
</DictionaryEntry>
<DictionaryEntry>
<Key xsi:type="xsd:string">Department</Key>
<Value xsi:type="xsd:string">IT</Value>
</DictionaryEntry>
<DictionaryEntry>
<Key xsi:type="xsd:string">AccountName</Key>
<Value xsi:type="xsd:string">abc</Value>
</DictionaryEntry>
<DictionaryEntry>
<Key xsi:type="xsd:string">PrincipalType</Key>
<Value xsi:type="xsd:string">User</Value>
</DictionaryEntry>
</ArrayOfDictionaryEntry>
'>
</div>
</div>