Reading XML to a Dictionary

后端 未结 2 675
有刺的猬
有刺的猬 2021-02-08 11:26

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,

2条回答
  •  一整个雨季
    2021-02-08 12:03

    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:

    
        
        
    
    

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

    List defs = database.Elements("def");
    

    up to here, you got:

    
    
    

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

    foreach(XElement def in defs)
    {
        // Here you have each def 
        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.

提交回复
热议问题