如何用javascript中的`find`解析xml中的属性?

时间:2017-04-18 19:58:31

标签: javascript html xml xml-parsing

我正在学习javascript而且我有这样的小info.xml

<Check>
    <Meta>
        <Admin>William Taylor</Admin>
        <ID>1234</ID>
    </Meta>
    <Allusers>
        <User>
            <Moved count="9"/>
        </User>
        <Total old="8" new="10"/>
    </Allusers>
</Check>

如何使用此方法从上面的.xml加载包含属性count(9),old(8)和new(10)的数据?

var xml="<Check><Meta><Admin>William Taylor</Admin><ID>1234</ID></Meta><Allusers><User><Moved count='9' /></User><Total old='8' new='10'/></Allusers></Check>";
var xmlDoc = $.parseXML(xml)
$xml = $( xmlDoc ),
$admin = $xml.find("Admin");
$id = $xml.find("ID");
$("#Admin").append($admin.text());
$("#ID").append($id.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class ='frame'>
    <div class='div1'>
        <table class='table1'>
            <tr>
                <td>Admin</td>
                <td id="Admin"> </td>
            </tr>
            <tr>
                <td>ID</td>
                <td id="ID"> </td>
            </tr>
            <tr>
                <td>No. moved users</td>
                <td id="count"> </td>
            </tr>
            <tr>
                <td>No. old users</td>
                <td id="old"></td>
            </tr>
            <tr>
                <td>No. new users</td>
                <td id="new"></td>
            </tr>
        </table>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

你可以使用下面的选择器来获得你想要的东西,使用相同的想法:

$moved = $xml.find('Moved').attr('count');
$old = $xml.find('Total').attr('old');
$new = $xml.find('Total').attr('new');