我如何将xml写成
<?xml version="1.0" encoding="UTF-8"?>
<calibration>
<ZoomLevel 250>0.0100502512562814</ZoomLevel 250>
<ZoomLevel 250>0.0100502512562814</ZoomLevel 250>
........
</calibration>
我知道如何把它写出去但是我不能把它写成一个循环,我需要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);
}
答案 0 :(得分: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 );
}
我通过传递这个词典测试了这段代码:
"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>
答案 1 :(得分:0)
正如Michiel在评论中指出的那样,您要创建的XML无效。截至W3C XML specification:
除了那些字符外,几乎所有字符都允许在名称中使用 要么是合理的,要么可以用作分隔符。
您可能希望生成类似的内容:
<?xml version="1.0" encoding="UTF-8"?>
<calibration>
<zoom level="250">0.0100502512562814</zoom>
<zoom level="260">0.0100502512562815</zoom>
</calibration>
使用这样的代码片段生成:
foreach (KeyValuePair<string, double> entry in dict)
{
var node = doc.CreateElement("zoom");
var attribute = doc.CreateAttribute("level");
attribute.Value = entry.Key;
node.InnerText = entry.Value.ToString(CultureInfo.InvariantCulture);
node.Attributes.Append(attribute);
productsNode.AppendChild(node);
}