3

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?

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.