user801116
user801116

Reputation:

List xml nodes and attribute name from xml

How to retreive node_names and attribute_names from a xml (not values of node or attributes) Is it possible using 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>

Upvotes: 2

Views: 1115

Answers (2)

Yoshi
Yoshi

Reputation: 54649

You could start with something like 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);
});

Upvotes: 3

Vap0r
Vap0r

Reputation: 2616

A quick search revealed this page which deals in XML Parsing with jQuery. Getting the node name is a little more difficult but a method for getting it is provided here. From a quick look, I'm assuming you'd want to do something along the lines of:

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

I believe this should work no problems.

Upvotes: 0

Related Questions