gpt4 book ai didi

c# - 在循环 C# 中编写 XML

转载 作者:太空宇宙 更新时间:2023-11-03 19:16:47 26 4
gpt4 key购买 nike

我将如何写出 xml

<?xml version="1.0" encoding="UTF-8"?>
<calibration>
<ZoomLevel 250>0.0100502512562814</ZoomLevel 250>
<ZoomLevel 250>0.0100502512562814</ZoomLevel 250>
........
</calibration>

我知道如何写出来,但我不能在一个循环中写出来,我需要自动取款机,我有用于编写 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);
}

最佳答案

正如其他人所说,您想要的 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 );
}

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

"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# - 在循环 C# 中编写 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15931640/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com