First off, I’m aware that there are some other threads right now on a similar topic, but they seem to be a bit more than I need and honestly I just can’t wrap my head around them.
I’d appreciate it if anyone could provide an “explain like I’m 5” explanation of some simple XML access via C#.
Say I’ve got the following XML:
<records>
<patient name="john" age="25" status="fine" />
<patient>
<name>jane</name>
<age>30</age>
<status>not fine</status>
</patient>
</records>
Now, I’ve got 2 sets of similar data here. This is because I’m not sure which is the best, or “proper” way to organize it. But, the goal is the same.
In C#, I’d like to be able to simply pull that data and assign it to a variable in Unity. For example, putting the “age” property into an int or the “status” into a string.
I’ve been reading some of the threads here and its just not “clicking” for me. I’d be grateful if someone could give me a very basic explanation on this.
Edit: I should add that I’d like to access the XML locally, rather than via a web page.
Thanks.
XmlDocument mydoc = new XmlDocument();
mydoc.Load("file.xml");
XmlNodeList nodelist = mydoc.SelectNodes("records/patient");
if (nodelist.Count > 0)
{
for (int i = 0; i < nodelist.Count; i++)
{
XmlNode node = nodelist[i];
XmlAttributeCollection collection= node.Attributes; // here attreibutes like age, name, status
}
}
Noooo - Serialization is your friend. Honest! 
using System.Xml.Serialization;
[XmlRoot(ElementName = "records")]
public class Records
{
[XmlElement(ElementName = "patient")]
public Patient[] Patients { get; set; }
}
// this assumes the 2nd example where properties
// are child nodes and not attributes
public class Patient
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "age")]
public int Age { get; set; }
[XmlElement(ElementName = "status")]
public string Status { get; set; }
}
Then to load all your data into a Records object-
Records records;
using (FileStream file = new FileSteam("data.xml", FileMode.Open))
{
XmlSerializer serial = new XmlSerializer(typeof(Records));
records = (Records)serial.Deserialize(file);
}
This discards all the XML related junk after it’s loaded and serialized and leaves you with a nice object that you can query and manipulate as much as you like. Also makes saving the data back to a file easier (XmlSerializer comes with a Serialize method that goes the other way).
using System.Linq;
// get the first record of a guy named 'john'
var john = records.Patients.First(p => p.Name == "john");
// get all patients that are 25 or older
var oldGuys = records.Patients.Select(p => p.Age >= 25);
Double edit - I see you’re in Philadelphia - me too! (close anyway)