2012-07-09 3 views
3

TreeView 컨트롤을 사용하여 GUI에 XML 파일을로드하려고합니다. 그러나 XML 파일에 독점 레이아웃을 사용하고 있습니다.XML 파일을 TreeView로 읽기

XML은 다음과 같이 구성되어있다 : 나는 XML을 사용하는 완전히 새로운 해요

Class "Example" 
    Property "exampleProperty1" 
    Property "exampleProperty2" 
    Property "exampleProperty3" 

:

<ConfiguratorConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <Section> 
     <Class ID="Example" Name="CompanyName.Example" Assembly="Example.dll"> 
      <Interface> 
       <Property Name="exampleProperty1" Value="exampleValue" /> 
       <Property Name="exampleProperty2" Value="exampleValue" /> 
       <Property Name="exampleProperty3" Value="exampleValue" /> 
      </Interface> 
     </Class> 
    </Section> 
</ConfiguratorConfig> 

나는 출력이 같은 구조화하고 싶습니다. 나는 지난 몇 시간 동안 웹을 검색해 왔으며 아무 결과도 도움이되지 못했습니다. 일부는 끝났지 만 등록 정보가 나타나지 않거나 노드 이름이 표시되지 않습니다.

Visual Studio 2005에서 C#으로 작성했습니다. 도움을 제공해 주셔서 감사합니다!

답변

3
당신을 XmlDocument를 사용하여 노드를 통해 반복 할 수

, 당신은 콘솔 응용 프로그램의 Main 메서드에서이 데모를 넣을 수 있습니다 :

 string xml = @"<ConfiguratorConfig xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""> 
<Section> 
    <Class ID=""Example"" Name=""CompanyName.Example"" Assembly=""Example.dll""> 
     <Interface> 
      <Property Name=""exampleProperty1"" Value=""exampleValue"" /> 
      <Property Name=""exampleProperty2"" Value=""exampleValue"" /> 
      <Property Name=""exampleProperty3"" Value=""exampleValue"" /> 
     </Interface> 
    </Class> 
</Section></ConfiguratorConfig>"; 

     XmlDocument doc = new XmlDocument(); 
     doc.LoadXml(xml); 

     foreach (XmlNode _class in doc.SelectNodes(@"/ConfiguratorConfig/Section/Class")) 
     { 
      string name = _class.Attributes["ID"].Value; 
      Console.WriteLine(name); 

      foreach (XmlElement element in _class.SelectNodes(@"Interface/Property")) 
      { 
       if (element.HasAttribute("Name")) 
       { 
        string nameAttributeValue = element.Attributes["Name"].Value; 
        Console.WriteLine(nameAttributeValue); 
       } 
      } 
     } 

는 .NET보다 높은 3.0 당신이하여 XDocument 클래스를 사용할 수있는 버전을 사용하는 경우 (선택할 수 있으면 추천 됨).

 XDocument xdoc = XDocument.Parse(xml); 
     foreach (XElement _class in xdoc.Descendants("Class")) 
     { 
      string name = _class.Attribute("ID").Value; 
      Console.WriteLine(name); 

      foreach (XElement element in _class.Descendants("Property")) 
      { 
       XAttribute attributeValue = element.Attribute("Name"); 
       if (attributeValue != null) 
       { 
        string nameAttributeValue = attributeValue.Value; 
        Console.WriteLine(nameAttributeValue); 
       } 
      } 
     } 
+0

Perfect! 내 TreeView 채우기 위해이 코드를 조정할 관리하고, 그것은 내가 필요한 것입니다. – Fraserr

+0

좋아요! 도와 줘서 기쁩니다 :) –