Getting XML data into combobox

前端 未结 2 1212
情深已故
情深已故 2021-01-24 08:12

I have a windows form with 3 comboboxes and a XML file as following



    
        

        
2条回答
  •  死守一世寂寞
    2021-01-24 08:45

    I prefer to use Linq2XML:

    Load the data into an XDocument:
    Either load from file:

    var xmlDocument = XDocument.Load(fileName);
    

    or load from a string

    var xmlDocument = XDocument.Parse( @"
    
        
            
                
                    Ctrl
                
                
                    Alt
                
                
                    Shift
                
            
        
        
            
                
                    Ctrl
                
                
                    Alt
                
                
                    Shift
                
            
        
        
            
                
                    a
                
                
                    b
                
                
                    c
                
            
        
    ");
    

    Then you can select desired items

    var mainItems = from key in xmlDocument.Descendants("key1")
                    select key.Value;
    var secKeyItems = from key in xmlDocument.Descendants("key2")
                    select key.Value;
    var alphaItems = from key in xmlDocument.Descendants("key3")
                    select key.Value;
    

    You can now bind each combo to the selected result, like this:

    comboBox1.DataSource = mainItems.ToList();
    

    You might want to wash your XML (to remove newlines and spaces)

    var mainItems = from key in xmlDocument.Descendants("key1")
                    select key.Value.Trim();
    var secKeyItems = from key in xmlDocument.Descendants("key2")
                    select key.Value.Trim();
    var alphaItems = from key in xmlDocument.Descendants("key3")
                    select key.Value.Trim();
    

提交回复
热议问题