在循环中编写XML c#

Col*_*rke 1 c# xml linq

我如何写出xml

<?xml version="1.0" encoding="UTF-8"?>
<calibration>
  <ZoomLevel 250>0.0100502512562814</ZoomLevel 250>
  <ZoomLevel 250>0.0100502512562814</ZoomLevel 250>
  ........
</calibration>
Run Code Online (Sandbox Code Playgroud)

我知道如何写出来,但我不能写出一个循环,我需要atm我有写的xml表是

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);
}
Run Code Online (Sandbox Code Playgroud)

Oma*_*mar 6

正如其他人所说,你想要的xml是无效的.我注意到的另一件事是,在你的例子中有两个节点,其级别缩放为250,这是字典的一个关键,你知道它应该是唯一的.但是我建议你使用更简单的LINQ to XML(System.Xml.Linq),那么:

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 );
}
Run Code Online (Sandbox Code Playgroud)

我通过传递这个字典测试了这段代码:

"250", 0.110050251256281
"150", 0.810050256425628
"850", 0.701005025125628
"550", 0.910050251256281
Run Code Online (Sandbox Code Playgroud)

结果是:

<?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>
Run Code Online (Sandbox Code Playgroud)