从jquery遍历xml节点

时间:2012-04-12 12:20:26

标签: javascript jquery xml

我的html代码就是这个

 <script type="text/javascript" src="js/jquery.js"></script>
 <script type="text/javascript">
 if (window.XMLHttpRequest)
 {
     xmlhttp=new XMLHttpRequest();
 } else {
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }

 xmlhttp.open("GET","brands.xml",false);
 xmlhttp.send();
 theXmlDoc=xmlhttp.responseXML; 
 function fillForm(){
     $(theXmlDoc).find('table[name=brands]').each(function(){
         alert($(this));//doesn't fire when brands.xml contains more than one entry of <table name="brands"> else shows Object object
     });

我的brands.xml是

  <table name="brands">
        <column name="BrandID">1</column>
        <column name="BrandName">AX</column>
        <column name="CompanyInfo">FDC</column>
        <column name="Composition">Cap</column>
 </table>
 <table name="brands">
        <column name="BrandID">2</column>
        <column name="BrandName">UP</column>
        <column name="CompanyInfo">Tor</column>
        <column name="Composition">Asp</column>
 </table>

brands.xml包含<table name="brands">警告的单个条目时显示对象对象,但当我包含多个表名时,如上所示,每个都没有被执行。

2 个答案:

答案 0 :(得分:2)

您的XML需要由单个节点包装:

<tables>
    <table name="brands">
        <column name="BrandID">1</column>
        <column name="BrandName">AX</column>
        <column name="CompanyInfo">FDC</column>
        <column name="Composition">Cap</column>
    </table>
    <table name="brands">
        <column name="BrandID">2</column>
        <column name="BrandName">UP</column>
        <column name="CompanyInfo">Tor</column>
        <column name="Composition">Asp</column>
    </table>
</tables>

您需要相应地调整JavaScript,以便在此包装节点内选择。

答案 1 :(得分:1)

您需要在表节点上方指定一个根节点。

喜欢

<root-node>
 <table name="brands">
        <column name="BrandID">1</column>
        <column name="BrandName">AX</column>
        <column name="CompanyInfo">FDC</column>
        <column name="Composition">Cap</column>
    </table>
    <table name="brands">
        <column name="BrandID">2</column>
        <column name="BrandName">UP</column>
        <column name="CompanyInfo">Tor</column>
        <column name="Composition">Asp</column>
    </table>
</root-node>

请参阅教程http://webhole.net/2009/12/16/how-to-read-xml-with-javascript/

相关问题