Reputation: 11
I'm trying to read a XML in C#, using a button in WPF. I have this XML file:
<?xml version="1.0" encoding="utf-8" ?>
<date>
<Disciplina nume="Disc1" cadru="Cadru1">
<Student>
<Nume>Student1</Nume>
<Nota>9</Nota>
</Student>
</Disciplina>
</date>
In the reading Button i have this code:
XmlTextReader rd = new XmlTextReader(@"Test.xml");
string dnume = "", dcadru = "", snume = "",snota="", element = "";
while ( rd.Read() )
{
switch (rd.NodeType)
{
case XmlNodeType.Element:
element = rd.Name;
break;
case XmlNodeType.Text:
if (element == "Disciplina")
{
dnume = rd.GetAttribute("nume");
dcadru = rd.GetAttribute("cadru");
}
else
if (element == "Student")
{
}
break;
case XmlNodeType.EndElement:
if (rd.Name == "Student1")
{
MessageBox.Show("");
}
break;
}
}
rd.Close();
The problem is that I don't know how to read the information from the Student node. Can you help me?
Upvotes: 0
Views: 107
Reputation: 16968
If you really need to use XmlReader
classes you can use a code like below in a Console Application:
var nestedLevel = 0;
var studentNestedLevel = 0;
using (var reader = XmlTextReader.Create(@"Test.xml"))
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
nestedLevel++;
if (studentNestedLevel > 0)
Console.Write("{0}: ", reader.Name);
if (reader.Name.ToLower() == "student")
studentNestedLevel = nestedLevel;
break;
case XmlNodeType.Text:
if (studentNestedLevel > 0)
Console.WriteLine("{0}", reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
if (studentNestedLevel > 0)
Console.WriteLine("{0}: {1}", reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
break;
case XmlNodeType.EndElement:
nestedLevel--;
if (reader.Name.ToLower() == "student")
studentNestedLevel = 0;
break;
}
}
}
Upvotes: 1