簡體   English   中英

如何在C#中解析此xml?

[英]How to parse this xml in c#?

我想將xml文件解析成字典,字典看起來像這樣

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

我如何從下面的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.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);
}

我會這樣做:

  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)

嘗試如下...它將為您提供幫助...

代碼:

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

輸出:

在此處輸入圖片說明

使用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));

這樣的事情應該起作用。 不要忘記添加一些錯誤處理,您可能希望從文件而不是硬編碼的字符串中加載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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM