2014-01-23 34 views
0

瞭解XML innertags的計數我有這樣的XML,它擁有5架要使用XmlDocument的

<?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> 

我在的XmlDocument加載XML文件,我想從上面陳列架總數XML。我想顯示5作爲輸出。

+0

是否必須XmlDocument的,使用的XDocument更輕盈。您可以使用xpath表達式來獲取XmlNodeList,並簡單計算其中的項目數。 – stevethethread

+0

@stevethethread:我試過了,var xpath =「// Interview/Rack」; XmlNodeList cnt = xworkload.DocumentElement.SelectNodes(xpath); int sum = 0; (cint中的XmlNode節點) sum + = Int32.Parse (「Racks總數:」+ sum.ToString()); – user42067

+0

您是否嘗試過cnt.Count? – MrClan

回答

0

這個我試過,最後它的工作..

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

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

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

當然,有很多方法可以做到這一點。 – stevethethread

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

使用你的代碼,如果你需要的是陳列架節點的數量:

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); 
      } 
     } 
    } 

這應該顯示在彈出的輸出爲5。

+0

爲您的方案,您可以使用任何xpath: * //機架*或 * //採訪/機架*或 *採訪/機架* 它應該都選擇所需的節點。 – MrClan