Question

I have this Xml, It has 5 Racks

<?xml version="1.0" encoding="utf-8"?>
<workload>  
  <Interview>
    <Rack Path="\Left_Rack\36 U.gif" Name="36" LName="36" Height="36" Selected="True" ID="8075" partnumber="AF046A" description="ABC Rack"  />        
    <Rack Path="\Left_Rack\42 U.gif" Name="42" LName="42" Height="42" Selected="False" ID="3185" partnumber="AS0912" description="DEF Rack" />
    <Rack Path="\Left_Rack\48 U.gif" Name="48" LName="48" Height="48" Selected="False" ID="7580" partnumber="AS0912" description="DEF Rack" /> 
    <Rack Path="\Left_Rack\52 U.gif" Name="52" LName="52" Height="52" Selected="False" ID="3892" partnumber="AS0912" description="DEF Rack" /> 
    <Rack Path="\Left_Rack\65 U.gif" Name="56" LName="56" Height="56" Selected="False" ID="9187" partnumber="AS0912" description="DEF Rack" />     
  </Interview>
</workload>

I have loaded the Xml file in XmlDocument, I want to display the total number of Racks from the above Xml. I want to display 5 as output.

Was it helpful?

Solution 2

I tried this, And Finally its working..

if(xworkload.DocumentElement.SelectSingleNode("Interview/Rack") !=null)
                    {

                        XmlNodeList cnt = xworkload.GetElementsByTagName("Rack");                                         

                        MessageBox.Show("The Total number of Racks are :" + cnt.Count.ToString());
                    }

OTHER TIPS

xworkload.SelectNodes("//Interview/Rack").Count

Using your code, if all you need is to display the number of Rack nodes :

XmlDocument xworkload = new XmlDocument();
private void btnTotalRack_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 
        dlg.FileName = "Document";
        dlg.DefaultExt = ".hpa";
        dlg.Filter = "Xml document (.hpa)|*.hpa";
        var result = dlg.ShowDialog(); //Opens the dialog box to select the xml file
        if (result == true)
        {
            try
            {
                xworkload.Load(dlg.FileName);  //load the Xml file in XmlDocument
                MessageBox.Show("The Total number of Racks are :" + xworkload.SelectNodes("//Interview/Rack").Count);
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
    }

This should display the output as 5 in the popup.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top