I have an xml file which contains the following structure
<Planet>
<Continent name="Africa">
<Country name="Algeria" />
<Country name="Angola" />
...
</Continent>
</Planet>
I need to add to it the rest of the continent tags with there containing cities. This is my code:
public static string continent;
public static List<string> countries = new List<string>();
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"D:\Projects IDE\Visual Studio\Tutorial\e-commerce\classModeling\GenerateXml file\GenerateXml file\bin\Debug\Planet.xml");
XmlNode xNode = xDoc.CreateNode(XmlNodeType.Element, "Continent", "");
XmlAttribute xKey = xDoc.CreateAttribute("name");
xKey.Value = continent;
xNode.Attributes.Append(xKey);
xDoc.GetElementsByTagName("Planet")[0].InsertAfter(xNode , xDoc.GetElementsByTagName("Planet")[0].LastChild);
foreach (var country in countries)
{
XmlElement root = xDoc.CreateElement("Country");
XmlAttribute xsKey = xDoc.CreateAttribute("name");
xsKey.Value = country;
root.Attributes.Append(xKey);
}
xDoc.Save(@"D:\Projects IDE\Visual Studio\Tutorial\e-commerce\classModeling\GenerateXml file\GenerateXml file\bin\Debug\Planet.xml");
My code creates all the tags but does not add the attributes.
And before anyone asks the continent variable and countries list contain the needed items I just felt it's not needed to display that part of the code two.
What am I doing wrong here?
EDIT
I managed to corect the code and now it work the attributes were not apearing because I gave both the the node attribute and element attribute the same name I changd the names , and now it works.