Writing XML in loop c#

c#, linq, xml

Solution

As the others said your wanted xml isn't valid. Another thing that I noticed is that in your example there are two nodes with the level zoom of 250 which is a key of the dictionary and as you know it should be unique. However I recommend you to use LINQ to XML (`System.Xml.Linq`) which is simpler, so what about:

public void XMLWrite( Dictionary<string, double> dict ) {
   //LINQ to XML
   XDocument doc = new XDocument( new XElement( "calibration" ) );

   foreach ( KeyValuePair<string, double> entry in dict )
     doc.Root.Add( new XElement( "zoom", entry.Value.ToString( ), new XAttribute( "level", entry.Key.ToString( ) ) ) );

   doc.Save( pathName );
}

I tested this code by passing this dictionary:

"250", 0.110050251256281
"150", 0.810050256425628
"850", 0.701005025125628
"550", 0.910050251256281

And the result is:

<?xml version="1.0" encoding="utf-8"?>
<calibration>
  <zoom level="250">0,110050251256281</zoom>
  <zoom level="150">0,810050256425628</zoom>
  <zoom level="850">0,701005025125628</zoom>
  <zoom level="550">0,910050251256281</zoom>
</calibration>

Problem

How would i write the xml out like ``` <?xml version="1.0" encoding="UTF-8"?> <calibration> <ZoomLevel 250>0.0100502512562814</ZoomLevel 250> <ZoomLevel 250>0.0100502512562814</ZoomLevel 250> ........ </calibration> ``` I know how to write it out but i cant write it out in a loop which i need to atm the i have for writting the xml sheet is ``` public void XMLWrite(Dictionary<string, double> dict) { //write the dictonary into an xml file XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlNode productsNode = doc.CreateElement("calibration"); doc.AppendChild(productsNode); foreach (KeyValuePair<string, double> entry in dict) { XmlNode zoomNode = doc.CreateElement("ZoomLevel"); XmlAttribute ZoomLevel = doc.CreateAttribute(entry.Key.ToString()); //XmlElement PixelSize = doc.CreateElement (entry.key = entry.Value.ToString()); zoomNode.Attributes.Append(ZoomLevel); productsNode.AppendChild(zoomNode); } doc.Save(pathName); } ```

Original source