I am trying to parse a XML file in C# using Visual Studio and show the data in a ListBox, but I don't know how to parse it when I'm dealing with a nested XML file.
This is the code from the XML file:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE root [
<!ELEMENT root (Persons*)>
<!ELEMENT Persons (name)>
<!ELEMENT IsMale (#PCDATA)>
<!ELEMENT Age (#PCDATA)>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT LikedPerson (name)>
]>
<root>
<Persons name ="Bob">
<IsMale>true</IsMale>
<Age>30</Age>
<LikedPerson name ="Iulia">
<IsMale>false</IsMale>
<Age>32</Age>
</LikedPerson>
</Persons>
</root>
The code I've written in C# successfully return me only the name, gender and age for every person, but I don't know how to write to show me also the person_liked:
private void LoadPersons()
{
XmlDocument doc = new XmlDocument();
doc.Load("Baza_de_cunostinte.xml");
foreach (XmlNode node in doc.DocumentElement)
{
string name = node.Attributes[0].Value;
int age = int.Parse(node["Age"].InnerText);
bool isMale = bool.Parse(node["IsMale"].InnerText);
// Persons likedPerson.name = Persons.node.Attributes[0].Value ?
// .....
listBox.Items.Add(new Persons(name, age, isMale, likedPerson));
}
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox.SelectedIndex != -1)
{
propertyGrid1.SelectedObject = listBox.SelectedItem;
}
}
This is the definition of the Persons.cs :
class Persons
{
public string Name { get; private set; }
public int Age { get; private set; }
public bool IsMale { get; private set; }
public Persons LikedPerson { get; private set; }
public Persons(string name, int age, bool isMale, Persons likedPerson)
{
Name = name;
Age = age;
IsMale = isMale;
LikedPerson = likedPerson;
}
}
LikedPersonoccur more than once?