How to read XML into a DataTable?

后端 未结 7 1593
星月不相逢
星月不相逢 2020-12-16 02:51

I have some XML in a string in memory exactly like this:


  EURCHF
  EURGBP         


        
7条回答
  •  春和景丽
    2020-12-16 03:31

    From here: http://www.dreamincode.net/code/snippet3186.htm

    // 
    /// method for reading an XML file into a DataTable
    /// 
    /// name (and path) of the XML file
    /// 
    public DataTable ReadXML(string file)
    {
        //create the DataTable that will hold the data
        DataTable table = new DataTable("XmlData");
        try
        {
            //open the file using a Stream
            using(Stream stream = new  FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //create the table with the appropriate column names
                table.Columns.Add("Name", typeof(string));
                table.Columns.Add("Power", typeof(int));
                table.Columns.Add("Location", typeof(string));
    
                //use ReadXml to read the XML stream
                table.ReadXml(stream);
    
                //return the results
                return table;
            }                
        }
        catch (Exception ex)
        {
            return table;
        }
    }
    

    You might want to take a look at DataTable.ReadXml method.

    EDIT: If you have xml object in memory you can use the ReadXml method directly. DataTable.ReadXml(MemoryStream Object);

    EDIT 2: I did the export. The following XML Schema is required:

    
    
      
        EURCHF
      
      
        EURGBP
      
      
        EURJPY
      
    
    

提交回复
热议问题