Ian
Ian

Reputation: 181

traverse though Javascript dom, details as attributes

I have a XML file structured as below. All the data is saved as attributes(unfortunately I cannot alter the structure). And I am reading this into Javascript. I have the following code but I am having troubles relating each plant to an agent. I have tried ChildNodes but that does not seem to be working with attributes.

    parser = new DOMParser();
    xmlDoc = parser.parseFromString(reader.result,"text/xml");

    var i;
    for (i = 0;i<xmlDoc.getElementsByTagName("Agent").length;i++)
    {
        console.log(xmlDoc.getElementsByTagName("Agent")[i].attributes);

        for (....)//some for loop to look at every plant for that agent.
        {

        }
    }

And the XML data:

<?xml version="1.0" encoding="utf-8"?>
<root>
 <Agent Id="1" Type="typeA" Area="Area1">
  <Portfolio>
   <Plant Type="Type1" SubType="SubType1" />
   <Plant Type="Type2" SubType="SubType2" />
 </Portfolio>
</Agent>
<Agent Id="2" Type="typeB" Area="Area2">
 <Portfolio>
  <Plant Type="Type3" SubType="SubType3" />
  <Plant Type="Type4" SubType="SubType4" />  
 </Portfolio>
</Agent>
</root>

Upvotes: 0

Views: 39

Answers (2)

Jadli
Jadli

Reputation: 860

xml=`<?xml version="1.0" encoding="utf-8"?>
<root>
 <Agent Id="1" Type="typeA" Area="Area1">
  <Portfolio>
   <Plant Type="Type1" SubType="SubType1" />
   <Plant Type="Type2" SubType="SubType2" />
 </Portfolio>
</Agent>
<Agent Id="2" Type="typeB" Area="Area2">
 <Portfolio>
  <Plant Type="Type3" SubType="SubType3" />
  <Plant Type="Type4" SubType="SubType4" />  
 </Portfolio>
</Agent>
</root>`

parser = new DOMParser();
xmlDoc = parser.parseFromString(xml,"text/xml");

// traverse agents
for (let agent of xmlDoc.getElementsByTagName("Agent"))
{
   // console.log(agent.attributes);

    // traverse plants
    for (let plant of agent.getElementsByTagName("Plant")) {
      console.log('agent type:', agent.getAttribute('Type'),'agent Area:', agent.getAttribute('Area'));

console.log('plant type:',plant.getAttribute('Type'),' plant SubType:',plant.getAttribute('SubType'))
    }
}

Upvotes: 0

Szaman
Szaman

Reputation: 2388

You can simply get all elements with tag name <Plant> nested inside your <Agent> tag.

parser = new DOMParser();
xmlDoc = parser.parseFromString(xml,"text/xml");

// traverse agents
for (let agent of xmlDoc.getElementsByTagName("Agent"))
{
    //console.log(agent.attributes);

    // traverse plants
    for (let plant of agent.getElementsByTagName("Plant")) {
      console.log('agent:', agent.attributes, 'plant:', plant.attributes);
    }
}

Check out a live example here: jsfiddle.

Upvotes: 1

Related Questions