问题
I have an xml file, and I need to be able to sort it in either a list or an array
The XML:
<Restaurant>
<name>test</name>
<location>test</location>
</Restaurant>
<Restaurant>
<name>test2</name>
<location>test2</location>
</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.
回答1:
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();
EDIT: 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")
};
Usage:
foreach(var restaurant in restaurants)
{
// use restaurant.Name or restaurant.Location
}
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.
回答2:
The answer by Sergey is very clear but if you want to load it from the saved file I think it will be helpful for you. Actually for loading a XML files to the array I used this method, But my array was double Jagged array. The code that I used is below I modified based on your resturant:
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 ;
}
By this function you can read all your data as below :
double [][] res = LoadXML(@"YOUR FILE PATH");
As you know the first and second element of each resturant is name and location I think accessing to them is now easy for you.
来源:https://stackoverflow.com/questions/21069499/put-xml-into-array