本文介绍了将xml放入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an xml file, and I need to be able to sort it in either a list or an array

XML:

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

所有餐厅的字段数和字段名称都相同,但是给定xml文件中的<Restaurant></Restaurant>数是未知的.

All the Restaurants will have the same number of fields and the same names for the fields, but the number of <Restaurant></Restaurant> in a given xml file is unknown.

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

In other words, I need an array or list and be able to do this:

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

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

While I don't need that syntax obviously, this is the functionality I'm trying to accomplish.

推荐答案

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

If you are trying to get names of restaurants and Restaurant elements are direct child of root element:

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

如果您试图解析整个餐厅对象:

If you are trying to parse whole restaurant objects:

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()调用将餐厅排列到数组中.

You can create instance of some Restaurant class instead of anonymous object here. Also you can put restaurants to array by simple restaurants.ToArray() call.

这篇关于将xml放入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 04:09