【问题标题】:put xml into Array将xml放入数组
【发布时间】:2014-01-30 21:54:13
【问题描述】:

我有一个 xml 文件,我需要能够在列表或数组中对其进行排序

XML:

<Restaurant>
   <name>test</name>
   <location>test</location>
</Restaurant>
<Restaurant>
   <name>test2</name>
   <location>test2</location>
</Restaurant>

所有餐厅都将具有相同数量的字段和相同的字段名称,但给定 xml 文件中 &lt;Restaurant&gt;&lt;/Restaurant&gt; 的数量是未知的。

换句话说,我需要一个数组或列表并且能够做到这一点:

String name = restaurantArray[0].name;
String location = restaurantArray[0].location;

虽然我显然不需要这种语法,但这是我想要完成的功能。

【问题讨论】:

  • 您到底想在字符串数组中放入什么?餐厅名称?

标签: c# xml xml-parsing linq-to-xml xml-deserialization


【解决方案1】:

Sergey 的回答非常清楚,但如果您想从保存的文件中加载它,我认为这对您会有所帮助。 实际上,为了将 XML 文件加载到数组中,我使用了这种方法,但我的数组是双锯齿数组。我使用的代码如下我根据您的餐厅修改:

  private static resturant[][] LoadXML(string filePath)
    {

        //Open the XML file
        System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);

        // First create a xml Serializer object

        System.Xml.Serialization.XmlSerializer xmlSer = new System.Xml.Serialization.XmlSerializer(typeof(resturant[][]));



       resturant[][] resturant = (resturant[][])xmlSer.Deserialize(fs);

        // Close the file stream

        fs.Close();


        return resturant ;

    }

通过此功能,您可以读取所有数据,如下所示:

double [][] res = LoadXML(@"YOUR FILE PATH");

您知道每个餐厅的第一个和第二个元素是名称和位置,我认为您现在可以轻松访问它们。

【讨论】:

    【解决方案2】:

    如果您尝试获取餐厅名称并且 Restaurant 元素是根元素的直接子元素:

    string[] names = xdoc.Root.Elements("Restaurant")
                         .Select(r => (string)r.Element("name"))
                         .ToArray();
    

    编辑:如果您尝试解析整个餐厅对象:

    var restaurants = from r in xdoc.Root.Elements("Restaurant")
                      select new {
                         Name = (string)r.Element("name"),
                         Location = (string)r.Element("location")
                      };
    

    用法:

    foreach(var restaurant in restaurants)
    {
        // use restaurant.Name or restaurant.Location
    }
    

    您可以在这里创建一些Restaurant 类的实例而不是匿名对象。您也可以通过简单的restaurants.ToArray() 电话将餐厅排列起来。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-20
      • 2013-07-06
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多