2013-07-16 6 views
0

나는 C#에 더 신선하다. 난 XML 문서를 구문 분석하고 childnodes의 특정 노드를 계산했습니다.XML 문서의 특정 노드에 대한 자식 노드를 계산하는 방법은 무엇입니까?

예컨대 : 나는 "직원"노드를 계산 어떻게

이 XML로
<Root> 
    <Id/> 
    <EmployeeList> 
     <Employee> 
     <Id/> 
     <EmpName/> 
     </Employee> 
     <Employee> 
     <Id/> 
     <EmpName/> 
     </Employee> 
     <Employee> 
     <Id/> 
     <EmpName/> 
     </Employee> 
    </EmployeeList> 
</Root> 

, ??

어떻게 구문 분석하고 C#에서 XmlDocument 클래스를 사용하여 솔루션을 얻을 수 있습니까?

XElement xElement = XElement.Parse(xml); 
int count = xElement.Descendants("Employee").Count(); 

이렇게하면 문자열에서 XML을 가정하여 XML 파일에있는 경우,

답변

4
int Count = doc.SelectNodes("Employee").Count; 
+0

이 정확한가요 ?? XmlElement docEle = doc.DocumentElement; XmlNodeList node = docEle.ChildNodes; (int i = 0; i cgsabari

2
XmlDocument doc = new XmlDocument(); 
doc.LoadXml(XmlString); 

XmlNodeList list = doc.SelectNodes("Root/EmployeeList/Employee"); 
int numEmployees = list.Count; 

, 당신이 할 수있는 LINQ to XML을 사용

doc.Load(PathToXmlFile); 
4

당신의 XPath를 사용할 수 있습니다

var xdoc = XDocument.Load(path_to_xml); 
var employeeCount = (double)xdoc.XPathEvaluate("count(//Employee)"); 
+0

int가 아닌 double을 캐스팅하는 이유는 무엇입니까? –

+0

@JohanLarsson 그것은'InvalidCastException'을 던집니다. 여기에있는 옵션은 double 형으로 캐스팅 된 후 int 형 (int) (double 형) xdoc.XPathEvaluate'로 변환됩니다. –

0

내가보기 엔 대신 System.Xml.Linq 라이브러리를 사용하는 것이 좋습니다. 그것은 당신이 사용하려는 것보다 훨씬 낫습니다. 당신이 당신하여 XDocument를로드 한 후, 당신은 단지 루트 노드를 얻을의 라인을 따라 뭔가 할 수있다 :이 코드는 정확한없는

//Parse the XML into an XDocument 
int count = 0; 

foreach(XElement e in RootNode.Element("EmployeeList").Elements("Employee")) 
    count++; 

을,하지만 당신은 더 복잡한 예 여기를 찾아보실 수 있습니다 : http://broadcast.oreilly.com/2010/10/understanding-c-simple-linq-to.html

관련 문제