Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding attribute to existing XMLNodes

Hi I am trying to add an attribut to several tags in an existing xml file.Here is the xml structure:

<Planet>
  <Continent ContinentName="Africa">
    <Country CountryName="Algeria" />
    <Country CountryName="Angola" />
     ...
  </Continent>
  <Continent ContinentName="Europe">
    <Country CountryName="France" />
    <Country CountryName="England" />
    ...
  </Continent>
  ...
</Planet>

I am trying to add an Id attribut to each of the country tags.Here is my code:

public static List<Cities> cities = new List<Cities>();

XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"D:\Projects IDE\Visual Studio\Tutorial\e-commerce\classModeling\GenerateXml file\GenerateXml file\bin\Debug\Planet.xml");
XmlAttribute xKey = xDoc.CreateAttribute("Id");
XmlElement root = xDoc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//Country");
int count = 0;

foreach( XmlNode node in nodes ) {
    string name = node.Attributes["CountryName"].Value;

    foreach (var cityObj in cities)
    {
        xKey.Value = cityObj.cityInitial;

        if(name == cityObj.cityName)
        {
            count++;
            node.Attributes.Append(xKey);
            Console.WriteLine(count);
        }
    }

}

xDoc.Save(@"D:\Projects IDE\Visual Studio\Tutorial\e-commerce\classModeling\GenerateXml file\GenerateXml file\bin\Debug\Planets.xml");

The problems is that this code only adds the id to the last element in the XML file. Now at first I tought that's because only one condition is true but then I added a counter and it turns out that that condition is true 179 times.If that is the case why am I getting only one attributt added at the finish?

like image 816
Nistor Alexandru Avatar asked Nov 21 '25 13:11

Nistor Alexandru


1 Answers

You should place XmlAttribute xKey = xDoc.CreateAttribute("Id"); inside the loop

like image 154
Teddy Avatar answered Nov 23 '25 01:11

Teddy