2012-07-09 54 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