2014-04-11 10 views
0
<career code="17-1011.00"> 
    <code>17-1011.00</code> 
    <title>Architects</title> 
    <tags bright_outlook="false" green="true" apprenticeship="false" /> 
    <also_called> 
     <title>Architect</title> 
     <title>Project Architect</title> 
     <title>Project Manager</title> 
     <title>Architectural Project Manager</title> 
    </also_called> 
    <what_they_do>Plan and design structures, such as private residences, office buildings, theaters, factories, and other structural property.</what_they_do> 
    <on_the_job> 
     <task>Consult with clients to determine functional or spatial requirements of structures.</task> 
     <task>Prepare scale drawings.</task> 
     <task>Plan layout of project.</task> 
    </on_the_job> 
</career> 

이 XML을 ONet에서 반환했으며 사용할 정보를 구문 분석하고 싶습니다. 다음은 Onet XML 인 'input'을 사용하여 아래 태그의 내부 텍스트를 분석하고 구문 분석하도록 작성한 코드입니다.내부 XML 태그 구문 분석 C#

XmlDocument inputXML = new XmlDocument(); 
     inputXML.LoadXml(input); 
     XmlElement root = inputXML.DocumentElement; 
     XmlNodeList titleList = root.GetElementsByTagName("also_called"); 
     for (int i = 0; i < titleList.Count; i++) 
     { 
      Console.WriteLine(titleList[i].InnerText); 
     } 

크기가 4 인 NodeList가 필요합니다. 그러나 결과를 인쇄 할 때 결과는 1 크기입니다. "ArchitectProject ArchitectProject ManagerArchitectural Project Manager"

XMLNodeList titleList를 잘못 구성 했습니까? XML 트리를 더 자세히 트래버스하고 처리하여 'also_called'아래에 'title'태그의 내부 값을 가져올 수 있습니까?

답변

2

also_called이라는 요소가 있습니다. 목록에 이러한 요소가 하나만 있습니다. 당신이 원하는 것은 also_called 노드의 자식을 얻는 것입니다. 예를 들어

: 또한

XmlNodeList also_calledList = root.GetElementsByTagName("also_called"); 
XmlNode also_calledElement = also_calledList[0]; 
XmlNodeList titleList = also_calledElement.ChildNodes; 

foreach (XmlNode titleNode in titleList) 
{ 
    Console.WriteLine(titleNode.InnerText); 
} 

, XML 대신 XmlDocumentXDocument 및 LINQ를 사용하는 것이 좋습니다 - 사용하는 것이 훨씬 간단하다 :

XDocument root = XDocument.Parse(input); 

foreach (XElement titleNode in root.Descendants("also_called").First().Elements()) 
{ 
    Console.WriteLine(titleNode.Value); 
} 
+0

XDocument 제안을위한 +1 –

0

당신은 단지의 XPath의 조금이라도 필요 . 그러면 의 하위 노드 인 title 노드가 모두 선택됩니다.

 XmlDocument inputXML = new XmlDocument(); 
     inputXML.LoadXml(input); 

     foreach(var node in root.SelectNodes("also_called[1]/title")) 
     { 
      Console.WriteLine(node.InnerText); 
     } 

그것은 당신이 GetElementsByTagName 또는 ChildNodes와 그 동류를 사용해야 및/또는 당신이 원하는 것을인지 파악하기 위해 노드를 검사하려고 것이 드물다. XmlDocument으로 Xml을 탐색하는 것은 모두 XPath을 사용하는 것과 관련하여 특정 조건을 충족하는 노드를 가져올 때 상당히 지정할 수 있습니다. 나무와 내용의 구조면에서

+0

두 코드를 모두 시도했지만 두 답변을 모두 확인할 수는 없으며 아직 평판이 없습니다. 무리 감사! – user3524976