Hello there guys, im having little problem and help would be appreciated :)
I have few tags

<name>
<capacity>
<lectureslot>
<tutorialslot>

and so on, and i want to read each tag separatly into separate field(label), or listbox.

Here is part of my XML
<?xml version="1.0" encoding="utf-8"?>

<timetable>
    <module code="3SFE504">
        <name>Algorithms and Data Structures</name>
        <capacity cap="5">5</capacity>
        <semester sem="1">1</semester>
        <prerequisite preq="none">none</prerequisite>
        <lectureslot ls="0">Mon 9.00-11.00</lectureslot>
        <tutorialslot ts="1">Mon 11.00-13.00</tutorialslot>
    </module>

And my source code is

private void show_Click(object sender, EventArgs e)

           {
                //Clear all of the items out of the list box
                modulelist.Items.Clear();
                //String workingDir = Directory.GetCurrentDirectory();
                //XmlTextReader textReader = new XmlTextReader(workingDir + @"\xmlmodulelist.xml");


                //the path to the xml file
                string path = "xmlmodulelist.xml";
                XmlDocument CXML = new XmlDocument();
                CXML.Load(@"xmlmodulelist.xml");

                //Open the filestream
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                //load the xml into the XmlDocument    
                CXML.Load(fs);                
                for (int i = 0; i < CXML.DocumentElement.ChildNodes.Count; i++)
                  {
                    //Add the innertext of the xml document to the listbox
                    //modulelist.Items.AddRange(new object[] { CXML.DocumentElement.ChildNodes[i].InnerText });
                    //XmlNode name = CXML.GetElementsByTagName("name")[0];
                   modulelist.Items.AddRange(new object[] { CXML.DocumentElement.GetElementsByTagName("name")[0]});                
                   //  modulelist.Items.AddRange(XmlNodeType.Text);  

                  }

                //Close the filestream
                fs.Close(); 



    }

And when show_click button is pressed it loads into listbox this

System.Xml.Xml.Element instead of Name Why is that ??

Dani AI

Generated

Short diagnosis: the ListBox showed "System.Xml.Xml.Element" because an XmlElement (an object) was added instead of a string. WinForms ListBox calls ToString() on items; XmlElement.ToString() yields the type name. The intended text is the element content or an attribute value — use the element’s InnerText/InnerXml or read its attribute.

A compact way to extract the <name> text and the capacity attribute without adding the node object directly:

foreach (XmlNode module in doc.DocumentElement.SelectNodes("module"))
{
    listBox.Items.Add(module.SelectSingleNode("name").InnerText);
    string cap = ((XmlElement)module.SelectSingleNode("capacity")).GetAttribute("cap");
    // assign cap to a label or add to another list
}

Clarifying notes and tips:

  • XmlNode.Value is null for element nodes; it’s meaningful for text/attribute nodes. Use InnerText (plain text) or InnerXml (markup) for element content.
  • To read attributes use GetAttribute or node.Attributes["cap"].Value after a null check.
  • Avoid loading the same XmlDocument twice (calling Load(path) and then Load(stream) is redundant). Use a single Load call or a using FileStream if needed.
  • For cleaner UIs, consider mapping modules to a small class and data-binding the list (set DisplayMember), or use LINQ to XML as suggested for concise queries.
  • Always null-check SelectSingleNode/SelectNodes results to prevent NullReferenceException; inspect nodes in the debugger to confirm NodeType and InnerText.

This explains why saw the type name and gives practical ways to extract the actual values.

Recommended Answers

All 3 Replies

Do you need to ad a .value to the end of it?

Do you need to ad a .value to the end of it?

?? add value where? i dont get sorry.

Anyway i have solved this, i scrapped the whole program and took different approach to it. ;) its now solved ;)

Well, OK.
If you ever decide to revisit XML, consider something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace DW_419550_CS_CON
{
   class Program
   {
      static void Main(string[] args)
      {
         XDocument doc = XDocument.Load(@"..\..\XMLFile1.xml");

         List<XElement> lst_xeModule = doc.Descendants("timetable").Descendants("module").Elements().ToList();

         lst_xeModule.ForEach(xe =>
         {
            // Print all element names and their values
            Console.WriteLine("\n" + xe.Name.ToString().PadRight(10, ' ') + "= " + xe.Value);

            // Print all attribute names and their values 
            xe.Attributes().ToList().ForEach(att => Console.WriteLine("\t" + att.Name + " = " + att.Value));
         });
      }
   }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.