David David - 1 month ago 5
Javascript Question

Appending is not happening in XML tag

I have a xml data which is given below.

<Sports>
<Oplympics>

<CONT Team="All" Country="Some" FLG = "0">
<TeamData Data="1" Data="2" Data="3"/>
</CONT>


<CONT Team="Aus" Country="Australia" FLG = "0">
<TeamData Player="X1" Player2 = "X2"/>
</CONT>

<CONT Team="Eng" Country="England" FLG = "0">
<TeamData Player="Y1" Player2 = "Y2"/>
</CONT>
</Oplympics>



What I want is to take a first tag of
TeamData
from CONT and add to all the CONT from 2nd to end. The sample output will be like

<Sports>
<Oplympics>

<CONT Team="All" Country="Some" FLG = "0">
<TeamData Data="1" Data="2" Data="3"/>
</CONT>


<CONT Team="Aus" Country="Australia" FLG = "0">
<TeamData Player="X1" Player2 = "X2"/>
<TeamData Data="1" Data="2" Data="3"/>
</CONT>

<CONT Team="Eng" Country="England" FLG = "0">
<TeamData Player="Y1" Player2 = "Y2"/>
<TeamData Data="1" Data="2" Data="3"/>

</CONT>
</Oplympics>




I am trying this code. Here I am getting TeamData and then in for loop it is setting for first element but second it is not entering in loop. Am I missing anything. Can any body please help

var TeamData = Xml.getElementsByTagName('CONT')[0];
var CONTTag = Xml.getElementsByTagName('CONT');
for(var i=1; i<CONTTag.length-1; CONTTag++){
CONTTag[i].append(TeamData);
}

Answer

There are a few issues with you code:

  1. Syntax error in the first line - remove the '.' between closing bracket and opening square bracket.
  2. The TeamData variable doesn't actually contain the TeamData node - the selector needs to be changed.
  3. The loop should start at 1, not zero, as the first CONTTag node is the one you are copying from.
  4. The loop should increment i, not CONTTag.

Here is your code with those fixes in place:

var TeamData = Xml.getElementsByTagName('TeamData')[0];
var CONTTag = Xml.getElementsByTagName('CONT');
for (var i = 1; i < CONTTag.length; i++) {
  CONTTag[i].append(TeamData.cloneNode());
}

A couple of other general comments:

  1. Your XML is missing a closing tag.
  2. XML nodes shouldn't have attributes with duplicate names - so your TeamData node is invalid XML at the moment.
Comments