从XML文件中调用某些元素?

时间:2014-08-06 19:57:05

标签: javascript jquery html xml

XML的新手,但我正在使用下面列出的XML文件。

有没有办法可以从每家公司提取某些信息?

代表。我只想要显示行业元素的信息

<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> 

1 个答案:

答案 0 :(得分:1)

例如:

var xmlText = $('#xmlData').text();
var $xmlData = $.parseXML(xmlText)

$('company', $xmlData).each(function(index, company) {
    console.log($('industry', company).text())
});

请参阅小提琴here了解详细示例

<强>更新

将结果打印到表格:

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())
});

更新了小提琴here