How can I transform XML into a List or String[]?

后端 未结 8 1743
半阙折子戏
半阙折子戏 2020-12-01 08:19

How can I transform the following XML into a List or String[]:


  1
  2<         


        
8条回答
  •  温柔的废话
    2020-12-01 09:05

    Here's a way to get typed array from xml by using DataSets. (in this example array of doubles)

    DataSet dataSet = new DataSet()
    DoubleArray doubles = new DoubleArray(dataSet,0);
    
    dataSet.ReadXml("my.xml");
    double a = doubles[0];
    
    
    
    public class DoubleArray
    {
      DataSet dataSet;
      int tableIndex;
      public DoubleArray(DataSet dataSet,int tableIndex)
      {
        this.dataSet=dataSet;
        this.tableIndex=tableIndex;
      }
    
      public double this[int index]
      {
        get
        { 
          object ret = dataSet.Tables[tableIndex].Rows[index];
          if(ret is double?) 
            return (ret as double?).Value;
          else
            return double.Parse(ret as string);
        }
        set
        {
          object out = dataSet.Tables[tableIndex].Rows[index];
          if(out is double?)
            dataSet.Tables[tableIndex].Rows[index] = (double?)value;
          else
            dataSet.Tables[tableIndex].Rows[index] = value.ToString();
        }
      }
    }
    

    Of course parsing doubles and converting them back to strings all the time might be considered as blasphemy by some programmers... Even for me it was hard not to think about such waste of resources... but I guess sometimes it's better to just turn another away.. don't stress it :)

提交回复
热议问题