C# - Reading XML file
c#, linq, xml, xml-parsing
Solution
There are three problems in your current code:
- You're asking the document for the `Item` elements, instead of the document root element
- You're asking for `Item` elements instead of `item` elements
- You're asking for the `Value` attribute instead of the `value` attribute
I'd also not use a query expression for this, as it's making things more complicated than they need to be:
var items = statusInfo.Root.Elements("item")
.Select(node => new Item {
Name = (string) node,
Value = (string) node.Attribute("value")
})
.ToList();
Problem
I'm trying to read an XML file in order to integrate data into Windows Phone App. I followed some other topics but I cannot get it to work (I feel I'm almost at the point but still missing something). The XML I'm trying to read is: ``` <?xml version="1.0" encoding="utf-8"?> <items> <item value="0">status</item> <item value="210">online</item> <item value="22h 49m 49s">uptime</item> <item value="90">latency</item> <item value="423">maxplayers_ever</item> <item value="263">maxplayers_week</item> <item value="252">maxplayers</item> </items> ``` It contains information for a game server. I'm reading it from an URL, that's the code I use: ``` public class Item { public string Name { get; set; } public string Value { get; set; } } private void LoadXMLFile() { WebClient wc = new WebClient(); wc.DownloadStringCompleted += HttpsCompleted; wc.DownloadStringAsync(new Uri("https://www.forgottenlands.eu/data.xml.php")); } private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { this.Items.Add(new ItemViewModel() { LineOne = "TEST I REACH HTTPS" }); XDocument statusinfo = XDocument.Parse(e.Result, LoadOptions.None); List<Item> items = (from node in statusinfo.Elements("Item") select new Item { Name = (string)node.Value, Value = (string)node.Attribute("Value") }).ToList(); foreach (var item in items) this.Items.Add(new ItemViewModel() { LineOne = item.Name + " " + item.Value }); this.IsDataLoaded = true; } } public void LoadData() { // Sample data; replace with real data // the xml file contains your provided xml code LoadXMLFile(); } ``` It seems like that I go correctly into the `httpscompleted` function, but I don't get correctly the XML data.