2016-04-27 124 views
0

我需要得到特別<EmpTypeHeader>EmpList標籤和<EID>.C#XML元素計數的XML節點

。例如計數:

EID - 9991515720640 with 1st EmpTypeHeader(XML Node) tag Contains 2 EmpList Tag 
EID - 4534545454534 with 2nd EmpTypeHeader(XML Node) tag Contains 1 EmpList Tag 
EID - 8998653323 with 3rd EmpTypeHeader(XML Node) tag Contains 1 EmpList Tag 

但是,當我選擇EMPList標籤計數它顯示的總計數4.

我的XML:

<Employee> 
    <EmployeeHeader> 
     <Date>2016-01-07</Date> 
     <Time>03:45:39</Time> 
    </EmployeeHeader> 
    <EmpTypeHeader> 
     <EID>9991515720640</EID> 
     <AAA>4</AAA> 
     <BBB /> 
     <EmpList> 
      <CCC>222</CCC> 
      <DDD>3333</DDD> 
      <EEE>2050-09-25</EEE> 
      <FFF>000</FFF> 
     </EmpList>  
     <EmpList> 
      <CCC>555</CCC> 
      <DDD>666</DDD> 
      <EEE>2050-09-25</EEE> 
      <FFF>000</FFF> 
     </EmpList> 
    </EmpTypeHeader> 
    <EmpTypeHeader> 
     <EID>4534545454534</EID> 
     <AAA>66</AAA> 
     <BBB /> 
     <EmpList> 
      <CCC>999</CCC> 
      <DDD>008</DDD> 
      <EEE>2050-09-25</EEE> 
      <FFF>000</FFF> 
     </EmpList>  
    </EmpTypeHeader> 
    <EmpTypeHeader> 
     <EID>8998653323</EID> 
     <AAA>9999</AAA> 
     <BBB /> 
     <EmpList> 
      <CCC>11333334</CCC> 
      <DDD>663312</DDD> 
      <EEE>2050-09-25</EEE> 
      <FFF>000</FFF> 
     </EmpList>  
    </EmpTypeHeader> 
</Employee> 

而且我的代碼:

private void ReadXMLEmp() 
{ 
    string eid = "9991515720640"; 
    string strFileName = @"D:\Raseeth\Test1.xml"; 
    xmlDocument = new XmlDocument(); 

    xmlDocument.Load(strFileName); 
    xmlNodeListEmpTypeHeader = xmlDocument.SelectNodes("//EmpTypeHeader");      
    if (xmlNodeListEmpTypeHeader != null) 
    { 
     int empListCount = 0; 

     foreach (XmlNode xmlNodeEmpTypeHeader in xmlNodeListEmpTypeHeader) 
     { 
      if (xmlNodeEmpTypeHeader["EID"] != null && xmlNodeEmpTypeHeader["EID"].InnerText.Trim() == eid) 
      { 
       empListCount = xmlNodeEmpTypeHeader.SelectNodes("//Position").Count; 
       Console.WriteLine("EmpList Count : " + empListCount); 
       bFlag = true; 
       break; 
      } 
     } 
    } 
} 
+0

沒關係,我是個瞎子出現。 (刪除以前的評論) – CherryDT

回答

0

問題是您的XPath表達式。 //Position將以該名稱查找文檔中的所有節點,而您只對當前節點的後代感興趣。

將其更改爲.//Position - .引用當前節點上下文。

話雖如此,LINQ到XML是一個更乾淨的解決方案,XPath和老XmlDocument API,例如:

var count = XDocument.Load("path/to/file.xml") 
    .Descendants("EmpTypeHeader") 
    .Where(x => (string) x.Element("EID") == "9991515720640") 
    .Descendants("Position") 
    .Count(); 
+0

我得到了結果...非常感謝 – Raseeth

0

如果你可以使用的.Net 3.5

XElement root = XElement.Load(strFileName); 
int total = 0; 
foreach(var eid in root.Descendants("EID").ToList()) 
{ 
    int count = eid.Parent.Elements("EmpList").Count(); 
    Console.WriteLine(eid.Value + " " + count.ToString()); 
    total += count; 
} 
Console.WriteLine("Total EmpList's: " + total.ToString()); 

我真的不理解的問題。你想通過EID計算EmpList的總數還是EmpList的總數?我做了兩個。

+0

我得到了結果...非常感謝 – Raseeth