如何从XML文件读取数组?

问题描述:

目前,我得到这个:如何从XML文件读取数组?

class robot 
{ 
    Configuratie config = new Configuratie(); 
    short[,] AlleCoordinaten = new short[3, 6] 
    { 
     {1,2,3,4,5,6}, 
     {6,5,4,3,2,1}, 
     {2,3,4,5,6,7} 
    }; 
} 

但我想提出一个XML的文件,数组,所以这是我的尝试:

class robot 
{ 
Configuratie config = new Configuratie(); 

    short[,] AlleCoordinaten = new short[3, 6] 
    { 
     {(config.GetIntConfig("robot","position1"))}, 
     {(config.GetIntConfig("robot","position2"))}, 
     {(config.GetIntConfig("robot","position3"))} 
    }; 
} 

配置文件:

class Configuratie 
    { 
     private XDocument xdoc; 

     public Configuratie() 
     { 
      xdoc = XDocument.Load("configuratie.xml"); 
     } 
    public int GetIntConfig(string desc1, string desc2) 
    { 
     int value = 0; 
     if (string.IsNullOrEmpty(desc1)) 
     { 
      value = 0; 
     } 
     if (!string.IsNullOrEmpty(desc1) && !string.IsNullOrEmpty(desc2)) 
     { 
      foreach (XElement node in xdoc.Descendants(desc1).Descendants(desc2)) 
      { 
       value = Convert.ToInt16(node.Value); 
      } 
     } 
     if (!string.IsNullOrEmpty(desc1) && string.IsNullOrEmpty(desc2)) 
     { 
      foreach (XElement node in xdoc.Descendants(desc1)) 
      { 
       value = Convert.ToInt16(node.Value); 
      } 
     } 
     return value; 
     } 
    } 

XML文件:

<robot> 
<position1>1</position1> 
<position1>2</position1> 
<position1>3</position1> 
<position1>4</position1> 
<position1>5</position1> 
<position1>6</position1> 
etc... 
<position3>7</position3> 
</robot> 

它仍然不起作用,你们能帮我解决我做错了什么,或者举个例子。我得到的错误是:我得到的错误是:一个长度为6的数组初始值设定项。并且:字段初始值设定项不能引用非静态字段方法或属性。我知道有一个更简单的方法,但我想用配置文件来完成。 我该怎么做?

+1

我已经回答了这个问题。 http://*.com/a/21552800/3010968 –

+0

你的数组初始化被搞砸了。编译器实际上是在告诉你这一点。 'GetIntConfig()'返回一个'int',你将传入一个数组,该数组需要6个整数的项。不是一个。第二个错误是因为您正在使用实例变量来设置另一个实例变量,如果编译器重新安排它们的初始化顺序会发生什么?那么你可能会访问一个尚未设置的变量,因此这也是不允许的。 – DGibbs

我看到一个简单的拼写错误的位置:

config.GetIntConfig("robot","positoin1") 

所以你要寻找的“positoin”和文件你有“地位”的。

我以为你放了(就像从这些数据中构建XML一样)。 这是如何做到这一点:

short[,] AlleCoordinaten = new short[3, 6] { {1,2,3,4,5,6}, {6,5,4,3,2,1}, {2,3,4,5,6,7} }; XElement elem = new XElement("robot"); for (int i = 0; i < AlleCoordinaten.GetUpperBound(0); i++) { for (int j = 0; j < AlleCoordinaten.GetUpperBound(1); j++) { elem.Add(new XElement(string.Format("position{0}",i +1),AlleCoordinaten.GetValue(i,j))); } }

+0

感谢您的awnser,我现在几乎在那里:http://*.com/questions/21552500/reading-an-array-from-an-xml-file。剩下的唯一问题是'名称'AlleCoordinaten'不存在于正确的内容' – user3201911