1

I want to parse an xml file into a dictionary the Dictionary looks like this

"250", 0.110050251256281
"150", 0.810050256425628
"850", 0.701005025125628
"550", 0.910050251256281

How can i parse the data above into a dictionary from the xml file below

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

any help would be much appreciated

4

5 回答 5

4

我会这样做:

  var xml = @"<?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>"

  var doc = XDocument.Parse(xml);
  var zooms = doc.Descendants("zoom")
                 .ToDictionary(x => x.Attribute("level").Value, x => x.Value)
于 2013-04-11T11:24:17.540 回答
4

您可以使用System.Xml.Linq.XDocument

System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load("your file");
var nodes = doc.Element("calibration").Elements("zoom");
Dictionary<string, double> myDictionary = new Dictionary<string, double>();

foreach (System.Xml.Linq.XElement item in nodes)
{
    var level = item.Attribute("level").Value;
    var val = double.Parse(item.Value);
    myDictionary.Add(level, var);
}
于 2013-04-11T11:21:28.307 回答
1

试试下面...它会帮助你...

代码 :

 System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
 doc.Load(Environment.CurrentDirectory + "//XML//Sample.xml");
 System.Xml.XmlNodeList CNodes = doc.SelectNodes("/calibration/zoom");
 Dictionary<int, string> dictionary = new Dictionary<int, string>();
 foreach (System.Xml.XmlNode node in CNodes)
   dictionary.Add(Convert.ToInt32(node.Attributes["level"].Value), node.InnerText);

输出 :

在此处输入图像描述

于 2013-04-11T11:31:56.160 回答
1

使用 Linq:

XDocument doc = XDocument.Load("XmlFile");
var elements = (from items in doc.Elements("calibration").Elements("zoom")
                select items).ToDictionary(x => x.Attribute("level").Value, x => Convert.ToDouble(x.Value));
于 2013-04-11T11:42:07.270 回答
0

像这样的东西应该工作。不要忘记添加一些错误处理,您可能希望从文件而不是硬编码字符串加载 xml。

string xml = @"<?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>";

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(xml);
var nodes = xmlDoc.SelectNodes("calibration/zoom");
var dicNodes = new Dictionary<string,string>();
foreach (System.Xml.XmlNode node in nodes)
{
    dicNodes.Add(node.Attributes["level"].Value, node.InnerText);
}
于 2013-04-11T11:33:15.203 回答