如何编写.js文件来从xml文件中读取

时间:2011-08-18 10:11:01

标签: javascript xml

我查看了示例,但我的xml文件与示例中使用的文件略有不同 我的xml文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<response>

<lst name="responseHeader">
  <int name="status">0</int>
  <int name="QTime">3</int>
  <lst name="params">
    <str name="facet">on</str>
    <str name="indent">on</str>
    <str name="start">0</str>
    <str name="q">*:*</str>
    <str name="facet.field">ISS_RATE_TXT</str>
    <str name="rows">10</str>
    <str name="version">2.2</str>
  </lst>
</lst>
<result name="response" numFound="2627" start="0">
  <doc>
    <str name="ASSET_CLASS_MNEM">OTHER     </str>
    <str name="ISS_RATE_TXT">OTH ASSETS</str>
    <str name="RCD_ID">4127      </str>
    <str name="RCD_NUM">1</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">INTL OIL</str>
    <str name="RCD_ID">4142      </str>
    <str name="RCD_NUM">2</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">BALANCE   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4145      </str>
    <str name="RCD_NUM">3</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">REC/PAY   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4149      </str>
    <str name="RCD_NUM">4</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">BALANCE   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4146      </str>
    <str name="RCD_NUM">5</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">REC/PAY   </str>
    <str name="ISS_RATE_TXT">CASH</str>
    <str name="RCD_ID">4148      </str>
    <str name="RCD_NUM">6</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">EQ FUNDS</str>
    <str name="RCD_ID">4143      </str>
    <str name="RCD_NUM">7</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">EQ FUNDS</str>
    <str name="RCD_ID">4144      </str>
    <str name="RCD_NUM">8</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">PUB/BRD</str>
    <str name="RCD_ID">4135      </str>
    <str name="RCD_NUM">9</str>
  </doc>
  <doc>
    <str name="ASSET_CLASS_MNEM">EQUITY    </str>
    <str name="ISS_RATE_TXT">OTH FIN</str>
    <str name="RCD_ID">4134      </str>
    <str name="RCD_NUM">10</str>
  </doc>
</result>
</response>

有人可以告诉我们如何修改示例

中的xml-grid.js文件

1 个答案:

答案 0 :(得分:0)

首先;要求XML文件,它需要与您的javascript文件位于同一个Web服务器中(否则浏览器将无法加载XML文件)。

要将XML文件加载到javascript,您需要使用XMLHttpRequest object,但如果您想在IE5和IE6中获得支持,则需要执行一些ActiveX控件魔法。以下是如何使用XMLHttpRequest执行此操作的示例:

var request = new XMLHttpRequest();
  // create the request object

request.open('GET', '/xml-grid.js', false);
  // open http session to the file

request.send(null);
  // Send the request (with nothing)

if (request.status == 200) {
  // if request was okay

    console.log(request.responseText);
      // write to console the response in text

}