I would do this with LINQ to XML.
To use it, you need to add a reference to System.Xml.Linq (in VS, right-click References -> Add Reference -> check System.Xml.Linq).
You don't need to convert the List into an array, but of course, you can, if you want. That's done simply with the list.ToArray()
method.
The writing-to-file code would be:
List<ListItem> list = new List<ListItem>();
// (the list is populated)
XDocument xDocument = new XDocument(); // create empty document
XElement root = new XElement("list"); // add root element, XML requires one single root element
xDocument.Add(root); // add root to document
foreach(var listItem in list)
{
var xElement = new XElement("list-item", // <list-item />
new XAttribute("id", listItem.ItemID), // id="id"
new XAttribute("quantity-sold", listItem.QuantitySold), // quantity-sold=5
new XAttribute("gallery-url", listItem.GalleryURL) // gallery-url="foo/bar"
);
root.Add(xElement); // add list-item element to root
}
xDocument.Save("Helpers/CachedResults/File.xml"); // save file
Note that the directory must exist for Save
to work!
Then parsing:
List<ListItem> list = new List<ListItem>();
XDocument xDocument = XDocument.Load("Helpers/CachedResults/File.xml"); // load from file
XElement root = xDocument.Element("list"); // get root element
foreach (XElement xElement in root.Elements("list-item")) // traverse through elements inside root element
{
list.Add(new ListItem // add list items
{
ItemID = xElement.Attribute("id").Value, // parse id
QuantitySold = Int32.Parse(xElement.Attribute("quantity-sold").Value), // parse int for QuantitySold
GalleryURL = xElement.Attribute("gallery-url").Value // parse url
});
}
And we're done!