【问题标题】:How to read generic xml using jquery如何使用 jquery 读取通用 xml
【发布时间】:2012-08-14 16:11:32
【问题描述】:

我有一个如下所示的通用 xml

 <Results>
  <Columns>
    <Column>Center ID</Column>
    <Column>Center Name</Column>
   /Columns>
  <Result>
    <Data>32452368</Data>
    <Data>Center1</Data>
  </Result>
  <Result>
    <Data>32452368</Data>
    <Data> Center2</Data>
  </Result>

</Results>

我正在尝试使用 jquery 从这个 xml 中读取数据。

 $(xml).find("Results/Result").each(function()
    {
    }

但我需要知道一些方法,以便按顺序读取它们,就像其中的第一个数据始终是中心 ID。 任何建议...

谢谢,

【问题讨论】:

    标签: jquery xml xml-parsing


    【解决方案1】:

    你在右边,each 方法迭代一个 jQuery 对象,按顺序为每个匹配的元素执行一个函数,但是 find 方法中选择器的语法不正确,试试这个:

    $(xml).find('Results > Result').each(function(){
       // do something here
    })
    

    【讨论】:

      【解决方案2】:

      这样的事情怎么样:

      var columns = [];
      
      // Go through the first Result tag and record the order of the columns:
      $(xml).find('Results > Result:first').each(function() {
          $(this).children('Data').each(function() {
              columns.push( $(this).text() );
          });
      });
      
      var results = [];
      $(xml).find('Results > Result:not(:first)').each(function() {
          // Result will map column names to values:
          var result = {};
          $(this).children('Data').each(function(i) {
              result[ columns[i++] ] = $(this).text();
          });
          results.push(result);
      });
      
      // Now results is an array of objects:
      // [
      //   { 'Center ID': 32452368', 'Center Name': 'Center1' },
      //   { 'Center ID': 32452368', 'Center Name': 'Center2' }
      // ]
      

      唯一让你误入歧途的是在你的选择器中使用了/,它不是一个有效的 CSS/jQuery 选择器。 &gt; 用于表示父子关系。 Results &gt; Result 是关键。

      【讨论】:

      • 感谢您的建议..我正在实施中,一旦完成将更新状态。谢谢
      • 有什么方法可以获取数据 Result:first,Result:second ,Result:third.. 就像使用 jquery 一样
      • 是的 :eq() 是选择器。
      猜你喜欢
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2011-07-14
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多