我如何在这里使用jQuery解析XML [英] How do I use jQuery to parse XML as I have here

查看:98
本文介绍了我如何在这里使用jQuery解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此(或它的某些变体)由我的PHP脚本输出.请注意,某些标记在不同的上下文中使用相同的名称:

This (or some variation of it) is output by my PHP script Notice that some tags use the same name in different contexts:

<conversations>
  <status>1</status>
  <conversation>
    <open>0</open>
    <status>1</status>
    <priority>1</priority>
  </conversation>
  <conversation>
    <open>1</open>
    <status>0</status>
    <priority>0</priority>
  </conversation>
</conversations>

<messages>
  <status>1</status>
  <message>
    <msgID>165</msgID>
    <userID>16></userID>
    <msg>How do I parse this?</msg>
  </message>
</messages>

首先,我需要遍历并为每个对话显示一个按钮.然后,我需要遍历并显示所选对话的所有新消息.我可以自己弄清楚逻辑.我只是不知道如何解析(爬升)XML.感谢您的帮助!

First, I need to loop through and display a button for each conversation. Then I need to loop through and display all the new messages for the selected conversation. I can figure the logic out on my own. I just don't know how to parse (climb around) the XML. Thanks for your help!

如果我说$("status",xml).text(),我怎么知道哪个<状态>标签是否被引用?我需要区分<对话>和<消息>.

If I say $("status",xml).text() how do I know which < status > tag is being referenced? I need to distinguish between < conversations > and < messages >.

推荐答案

  • .filter()筛选顶级节点
  • .children(),带有一个可选的选择器,以获取顶层的直接子集
  • .find()和一个选择器,以获取当前顶层节点以下任何级别的一组节点
  • .each()遍历当前顶层的那些
    • .filter() to filter through nodes at the top level,
    • .children() with an optional selector to get a set of immediate children of those at the top level
    • .find() with a selector to get a set of nodes at any level beneath those at the current top level
    • .each() to iterate over those at the current top level
    • 示例: http://jsfiddle.net/MTPdw/1/

      var $xml = $(xml);
      
      var conversations = $xml.filter('conversations');
      
      conversations.children('conversation').each(function() {
          alert($(this).find('status').text());
      });
      

      在做的时候:

      $("status",xml).text()
      

      ...它被转换为此:

      ...it gets converted into this:

      $(xml).find("status").text();
      

      由于顶层的节点是<conversations><messages>,因此它将搜索作为这两个元素的后代的所有<status>元素. .text()然后返回其累积的文本内容.

      Because the nodes at the top level are <conversations> and <messages>, it is searching for all <status> elements that are descendants of either of those. The .text() then returned their cumulative text content.

      这篇关于我如何在这里使用jQuery解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆