2012-07-09 74 views
3

我正在嘗試使用TreeView控件將XML文件加載到我的GUI中。 但是,我爲我的XML文件使用專有佈局。將XML文件讀入TreeView

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

我想輸出將結構類似:

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

我全新的使用XML。過去幾個小時我一直在網上搜索,結果都沒有幫助。有些已經接近,但可能屬性不會顯示,或節點的名稱將不會顯示,等等。

我在C#中編寫Visual Studio 2005. 感謝您的幫助!

回答

3

您可以通過使用XmlDocument的節點迭代,你可以把這個演示在一個控制檯應用程序的主要方法:

 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

完美!我設法調整這個代碼來填充我的TreeView,而這正是我所需要的。 – Fraserr 2012-07-09 14:38:33

+0

太棒了!我很高興幫助:) – 2012-07-09 16:31:33