本文介绍了在循环C#中编写XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何像这样写出xml

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>

我知道如何写出来,但是我无法在需要atm的循环中写出来,因为我写xml表是

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);
}

推荐答案

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

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

结果是:

<?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>

这篇关于在循环C#中编写XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:20
查看更多