Javascript 从XML文件调用某些元素?
对XML有点陌生,但我正在处理下面列出的一个XML文件 有没有一种方法可以让我从每家公司获取某些信息 例如,我只想显示来自行业元素的信息Javascript 从XML文件调用某些元素?,javascript,jquery,html,xml,Javascript,Jquery,Html,Xml,对XML有点陌生,但我正在处理下面列出的一个XML文件 有没有一种方法可以让我从每家公司获取某些信息 例如,我只想显示来自行业元素的信息 <companies> <company name="1" imageurl="logo"> <certification> Certified Best Employer </certification> <employee> 5,0000 </employee>
<companies>
<company name="1" imageurl="logo">
<certification> Certified Best Employer </certification>
<employee> 5,0000 </employee>
<industry> Risk Services </industry>
<html_url> http://www.google.com </html_url>
</company>
<company name="2" imageurl="logo">
<certification> Certified Best Employer </certification>
<employee> 5,0000 </employee>
<industry> Risk Services </industry>
<html_url> http://www.google.com </html_url>
</company>
<company name="3" imageurl="logo">
<certification> Certified Best Employer </certification>
<employee> 5,0000 </employee>
<industry> Risk Services </industry>
<html_url> http://www.google.com </html_url>
</company>
</companies>
认证最佳雇主
5,0000
风险服务
http://www.google.com
认证最佳雇主
5,0000
风险服务
http://www.google.com
认证最佳雇主
5,0000
风险服务
http://www.google.com
例如:
var xmlText = $('#xmlData').text();
var $xmlData = $.parseXML(xmlText)
$('company', $xmlData).each(function(index, company) {
console.log($('industry', company).text())
});
有关详细示例,请参见fiddle
更新
将结果打印到表格:
var xmlText = $('#xmlData').text();
var $xmlData = $.parseXML(xmlText)
$('company', $xmlData).each(function(index, company) {
$('#companies').append(
$(document.createElement('tr'))
.append(
$(document.createElement('td'))
.text($(this).attr('name'))
)
.append(
$(document.createElement('td'))
.text($('industry', this).text())
)
.append(
$(document.createElement('td'))
.text($('employee', this).text())
)
.append(
$(document.createElement('td'))
.text($('certification', this).text())
)
);
console.log($('industry', company).text())
});
更新的fiddle您能解释一下为什么选择了这组问号吗?jQuery选择器也适用于XMLDocuments:
$('company>industry',xmldocument)。每个(function(){/*do something*/})代码>。XMLDocument可以通过$请求。ajax
我只是选择了与应该提供的信息相关的问题标签,有没有更好的方法?谢谢Alex,而不是在控制台中查看。有没有办法让它打印出来,这样用户就可以看到了。例如,用户单击一个按钮,然后信息将打印在div或table中。谢谢Alex,这正是我要找的。我没能投票支持你但再次感谢你