2013-04-10 61 views
0

我將如何編寫XML出像編寫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); 
} 
+7

不是有效的XML標記。你的代碼現在輸出什麼? – 2013-04-10 16:43:36

回答

5

正如其他人說你想要的XML是無效的。我注意到的另一件事是,在您的示例中有兩個節點,其級別縮放爲這是字典的關鍵字,正如您所知它應該是唯一。 不過我建議你使用的LINQ to XMLSystem.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> 
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); 
}