如何从C#中的Xml文件读取数组 [英] How Do I Read An Array From A Xml-File In C#

查看:138
本文介绍了如何从C#中的Xml文件读取数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

At the moment iI got this:

    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}
        };
    }

But I want to put that array in a XML-file, so this is what I tried:

    class robot
    {
    Configuratie config = new Configuratie();

        short[,] AlleCoordinaten = new short[3, 6]
        {
           // errors are given here
            {(config.GetIntConfig("robot","positoin1"))},
            {(config.GetIntConfig("robot","positoin2"))},
            {(config.GetIntConfig("robot","positoin3"))}
        };
    }

configuration file:

        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 file:

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

It still isnt working, could you guys help me with what I did wrong and maybe give an example.

推荐答案

我建​​议您专注于序列化/编写XML文件或JSON文件,如下所述。



无论使用哪种格式,将文件反序列化/读回数组都很容易。



正如您所知,catch是.NET的Serialize工具不支持多维数组。



您可以轻松使用类似FastJSON的东西序列化器/反序列化器由Mehdi Gholam在CP上,处理多维数组:[ ^ ],生成的文件非常易读。



另一种技术是使你的数组​​成为一个锯齿状数组:即short [] []:可以被序列化;请参阅:[ ^ ]。如果您按照以下方式重新构建数组:
I'd suggest you focus on serializing/writing an XML file, or a JSON file, as outlined below.

Whichever format you used, de-serializing/reading the file back into an Array would be easy.

The "catch" is, as you may know, that .NET's Serialize facility does not support multi-dimensional Arrays.

You could easily use something like the FastJSON serializer/de-serializer by Mehdi Gholam here on CP, which will handle multi-dimensional Arrays: [^], and the resulting file would be fairly human-readable.

Another technique is to make your Array a jagged Array: i.e., short[][]: that can be serialized; see: [^]. If you re-structured your Array like this:
private short[][] AlleCoordinaten2 = new short[3][]
{
    new short[] {1,2,3,4,5,6},
    new short[] {6,5,4,3,2,1},
    new short[] {2,3,4,5,6,7}
};

然后您可以将其写入XMl像这样:

You could then write it to XMl like this:

// required
using System.IO;
using System.Xml.Serialization;

private string fPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

private void WriteArrayToXML_Click(object sender, EventArgs e)
{
    using (var stream = File.Create(fPath + @"/AlleCoordinaten.xml"))
    {
        var serializer = new XmlSerializer(typeof(short[][]));
        serializer.Serialize(stream, AlleCoordinaten2);
    }
}

生成的XML如下所示:

The resulting XML would look like this:

<arrayofarrayofshort xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <arrayofshort>
    <short>1</short>
    <short>2</short>
    <short>3</short>
    <short>4</short>
    <short>5</short>
    <short>6</short>
  </arrayofshort>
  <arrayofshort>
    <short>6</short>
    <short>5</short>
    <short>4</short>
    <short>3</short>
    <short>2</short>
    <short>1</short>
  </arrayofshort>
  <arrayofshort>
    <short>2</short>
    <short>3</short>
    <short>4</short>
    <short>5</short>
    <short>6</short>
    <short>7</short>
  </arrayofshort>
</arrayofarrayofshort>

有些人编写代码将多维数组转换为锯齿状数组进行序列化,反之亦然:你可以通过Googling找到对它的讨论:serialize jagged arrays。如果可能的话,我会尽量避免使用这些技术。

Some folks write code to convert multi-dimensional arrays to jagged arrays for serialization, and the reverse: you can find discussion of that by Googling on: "serialize jagged arrays." I'd try to avoid techniques like those, if possible.


你得到的错误是因为你在这里分配了一个包含3,6个短值的数组:
The error you are getting is because you are allocating an array of 3,6 short values here:
short[,] AlleCoordinaten = new short[3, 6]
{
  // errors are given here
  {(config.GetIntConfig("robot","positoin1"))},
  {(config.GetIntConfig("robot","positoin2"))},
  {(config.GetIntConfig("robot","positoin3"))}
};

那么,这是3行1个元素而不是3行6个元素。由于您没有预先分配值,因此您需要移动元素的实际分配。把它们放在一个方法体中并调用它 - 所以,你得到:

So, that's 3 rows of 1 element instead of 3 rows of 6 elements. As you aren't assigning the values up front, you would need to move the actual allocation of the elements. Put them in a method body and call that - so, you get:

short[,] AlleCoordinaten;

private void AllocateCoords()
{
  AlleCoordinaten = new short[3,6]
  {
    { 
      GetConfig("positoin1"),
      GetConfig("positoin2"),
      GetConfig("positoin3"),
      GetConfig("positoin4"),
      GetConfig("positoin5"),
      GetConfig("positoin6"),
    },
    { 
      GetConfig("positoin7"),
      GetConfig("positoin8"),
      GetConfig("positoin9"),
      GetConfig("positoin10"),
      GetConfig("positoin11"),
      GetConfig("positoin12"),
    },
    { 
      GetConfig("positoin13"),
      GetConfig("positoin14"),
      GetConfig("positoin15"),
      GetConfig("positoin16"),
      GetConfig("positoin17"),
      GetConfig("positoin18"),
    }
  }
}

private int GetConfig(string position)
{
  return config.GetIntConfig("robot", position);
}

如果我这样做,我会考虑使用不同的结构并从那里分配值,但这只是我 - 实际上,你在这里拥有的是一套魔法值;我对使用有意义的设置感到更舒服。

If I were doing this, I'd look at using a different structure and allocating the values from there, but that's just me - effectively, what you have here is a set of magic values; I'd feel more comfortable with meaningful settings.


这篇关于如何从C#中的Xml文件读取数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆