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

后端 未结 8 1738
半阙折子戏
半阙折子戏 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 :)

    0 讨论(0)
  • 2020-12-01 09:10

    Here is a way using XmlDocument :

    // A string containing the XML data
    string xml = "<Ids><id>1</id><id>2</id></Ids>";
    // The list you want to fill
    ArrayList list = new ArrayList();
    
    XmlDocument doc = new XmlDocument();
    // Loading from a XML string (use Load() for file)
    doc.LoadXml(xml); 
    // Selecting node using XPath syntax
    XmlNodeList idNodes = doc.SelectNodes("Ids/id");
    // Filling the list
    foreach (XmlNode node in idNodes)
        list.Add(node.InnerText);
    
    0 讨论(0)
提交回复
热议问题