2017-04-18 51 views
0

我學習JavaScript和我有小info.xml這樣的:如何在javascript中用`find`解析xml中的屬性?

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

如何可以加載具有屬性count數據(9),old(8)和從上述的.xml使用這種方法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

您可以使用下面的選擇得到你想要的東西,用同樣的想法:

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

非常感謝。 :) – amateur