Im trying to write out every childelement within the "fruit" rankings element. As the code is now, it goes to the first ranking element in my xml file and output the childelements within: But how do I by name go to "fruit" and write out it's childlements?
Xml
<ranking name="Browers>
<stat name="Chrome" />
<stat name="Firefox" />
<stat name="Safari" />
</ranking>
<ranking name="Fruit>
<stat name="Apple" />
<stat name="Orange" />
<stat name="Strawberry" />
</ranking>
Codebehind
XmlReader reader = XmlReader.Create(Server.MapPath("/temp/rankings.xml"));
while (true)
{
reader.ReadToFollowing("ranking");
string name = reader.GetAttribute("name");
if (name == "Fruit")
{
if (reader.ReadToDescendant("stat"))
{
do
{
litList.Text += reader.GetAttribute("name") + "<br />";
litList.Text += reader.GetAttribute("percent") + "<br />";
litList.Text += reader.GetAttribute("absolute") + "<br />";
} while (reader.ReadToNextSibling("stat"));
}
break;
}
}
It could be done like this:
if (reader.ReadToFollowing("ranking"))
{
do
{
Console.WriteLine("Ranking: " + reader.GetAttribute("name"));
if (reader.ReadToDescendant("stat"))
{
do
{
Console.WriteLine("Stat: " + reader.GetAttribute("name"));
} while (reader.ReadToNextSibling("stat"));
}
} while (reader.ReadToNextSibling("ranking"));
}
It may have some drawbacks. Instead of XmlReader you also could use XDocument: https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110).aspx