Reading XML to a Dictionary

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 17:20:00

问题


I need to read an XML file to a dictionary.

I read few guides and I only got confused from weird words that I don't understand (such as nodes, XML validation etc.). So, could you please walk me through?

I have an XML file which is written in this format:

<database>
    <def number="1" name="one"/>
    <def number="2" name="two"/>
</database>

As mentioned, I want to store it in a dictionary. How would I go about that?


回答1:


var data = XElement.Parse(xml)
    .Elements("def")
    .ToDictionary(
        el => (int)el.Attribute("number"),
        el => (string)el.Attribute("name")
    );

This:

  • parses the xml into an XElement (starting at <database>)
  • iterates over the <def ...> elements
  • forms a dictionary, using @number as the key (interpreting as an int), and @name as the value (as a string)
  • assigns this dictionary to data, which is implicitly typed as Dictionary<int,string>



回答2:


Your question is basic, but not inappropriate. Don't worry. I'll explain what you should do.

first you have to load this XML file (if it's on the disk). Otherwise you don't need this step

XDocument database = XDocument.Load(pathToYourXmlFile);

up to here, you got:

<database>
    <def number="1" name="one"/>
    <def number="2" name="two"/>
</database>

Then you have to get a list of all def elements:

List<XElement> defs = database.Elements("def");

up to here, you got:

<def number="1" name="one"/>
<def number="2" name="two"/>

Now, you should get each item of the list (each def in defs):

foreach(XElement def in defs)
{
    // Here you have each def <def number="x" name="y" />
    int number = def.Attribute("number").value;
    string name = def.Attribute("name").value;
}

the code to extract information from each def is:

int number = def.Attribute("number").value;
string name = def.Attribute("name").value;

Now that you have your number and name, just add it to your dictionary.

dictionary.Add(number, name);

Hope that helps.



来源:https://stackoverflow.com/questions/6578658/reading-xml-to-a-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!