从xml列出xml节点和属性名称

时间:2011-11-07 09:08:53

标签: javascript jquery html xml

如何从xml中检索node_names和attribute_names(不是节点或属性的值)是否可以使用jquery?

<Client>
    <product name="astro">
        <service_process name="ACID">
            <host>pable</host>
            <port>18848</port>
        </servcice_process>
        <service_process name="Mestro">
            <host>Mico</host>
            <port>18821</port>
        </servcice_process>
    </product>
</Client>

2 个答案:

答案 0 :(得分:2)

您可以从this开始:

var xml = '<Client><product name="astro"><service_process name="ACID"><host>pable</host><port>18848</port></servcice_process><service_process name="Mestro"><host>Mico</host><port>18821</port></servcice_process></product></Client>';

$(xml).each(function displayChildren (i, node) {
  console.log(node.nodeName);

  // traverse attributes
  $.each(node.attributes, function (j, attr) {
    console.log(attr.nodeName, attr.nodeValue);
  });

  // recursive call
  $(node).children().each(displayChildren);
});

答案 1 :(得分:0)

快速搜索显示this page使用jQuery处理XML解析。获取节点名称有点困难,但提供了获取节点名称的方法here。从快速的角度来看,我假设你想要做的事情是:

$(xml).each(function(){ //xml is the XML resource.
  if($(this).attr("name")!=""){
    alert("Name = " + $(this).attr("name"));
  }
  alert("Node = " + $(this).get(0).TagName);
});

我相信这应该没有问题。