How to add data to dictator in C #

How to add data to dictonary from xml file

scenerio:

I proclaimed a dictator such as

Dictonary<string,string> SampleDict=new Dictonary<string,string>(); 

and my xml file looks like

  <Data> <Element ValOne="1" ValTwo="0" /> <Element ValOne="2" ValTwo="2" /> <Element ValOne="3" ValTwo="4" /> <Element ValOne="4" ValTwo="6" /> <Element ValOne="5" ValTwo="8" /> <Element ValOne="6" ValTwo="10" /> <Element ValOne="7" ValTwo="12" /> <Element ValOne="8" ValTwo="14" /> <Element ValOne="9" ValTwo="16" /> <Element ValOne="10" ValTwo="18" /> </Data> 

I need to read the value of "ValOne" and "ValTwo" using LINQ and paste the same into the above stated dictation

and how to add the contents of this word to a list containing two columns.

Please help me do this

Thanks in advance

+4
source share
4 answers

You can use Linq for XML and ToDictionary for this.

 var doc = XDocument.Load("path to xml"); doc.Elements("Element").ToDictionary( elem => elem.Attribute("ValOne").Value, //Dictionary key elem => elem.Attribute("ValTwo").Value //Dictionary value ); 

This particular ToDictionary overload uses different lambdas to retrieve the keys and values ​​for the generated collection.

+6
source

Suppose you want ValOne to be the key and ValTwo to be the value?

 document.Descendants("Element") .ToList() .ForEach(e => SampleDict[e.Attribute("ValOne").Value] = e.Attribute("ValTwo").Value); 

It is assumed that you read your XML file in XDocument or XElement

+4
source
 XElement allData = XElement.Load("File.xml"); var els = allData.Descendants("Element"); foreach(var xe in els) { SampleDict[xe.Attribute("ValOne").Value] = xe.Attribute("ValTwo").Value; } 
+1
source

In this case, you can use data binding. Take a look at this article:
http://www.codeproject.com/KB/miscctrl/DBListViewForV2.aspx

All you have to do is ...

 var items = from xe in els select { ValOne = xe.Attribute("ValOne").Value, ValTwo = xe.Attribute("ValTwo").Value } var arr = items.ToArray(); //private DBListView dataBoundListView; //dataBoundListView.DataSource = this.bindingSource1; this.bindingSource1.DataSource = arr; 
+1
source

Source: https://habr.com/ru/post/1309623/


All Articles