Angel Angel - 1 month ago 6
C# Question

How do i get an XML attribute to display in a listbox c#

This is my code i got all the data from xml file to a list box the only one missing is the attribute i am having some difficulty trying to get the attribute to show up. not sure what exactly to do or what i am missing. i've never done xml before.

string startPath = Application.StartupPath + "\\ContactManager.xml";
XmlTextReader textReader = new XmlTextReader(startPath);
string Names = "";
string sex = "";

while (textReader.Read())
{
switch (textReader.NodeType)
{
case XmlNodeType.Attribute:
sex = textReader.GetAttribute("Sex");
break;
case XmlNodeType.Element:
Names = textReader.Name;
break;
case XmlNodeType.Text:
Console.WriteLine();
lbDisplay.Items.Add(sex + Names + ": " + textReader.Value);
break;
}

}


these are some of the elements in the xml file
Sex
is the attribute.

<Contact Sex="M">
<FirstName>Mickey</FirstName>
<LastName>Mouse</LastName>
<PhoneNumber>401-555-1212</PhoneNumber>
<FaxNumber>401-666-6666</FaxNumber>
<EmailAddress>mmouse@disney.com</EmailAddress>
</Contact>

Answer

You need to change your code to:

    string startPath = Application.StartupPath + "\\ContactManager.xml";
    XmlTextReader textReader = new XmlTextReader(startPath);
    string Names = "";
    string sex = "";

    while (textReader.Read())
    {
        switch (textReader.NodeType)
        {
            case XmlNodeType.Element:
                Names = textReader.Name;
              if(textReader.Name == "Contact") sex = textReader.GetAttribute("Sex");
                break;
            case XmlNodeType.Text:
                Console.WriteLine();
                lbDisplay.Items.Add(sex + Names + ": " + textReader.Value);
                break; 
        }

    }
Comments