0

我有一个结构的 xml 文件

<MainList>
<number>5<number/>
<first id="1" name="test" />
<second/>
<third/>
<MainList/>

现在我想通过消除“MainList”和“number”在树视图中显示它

我希望树以格式显示

first
  id
  name
second
third

我现在正在使用 xmlreader

4

1 回答 1

1

根据@AS-CII 此处提供的答案(将分层 xml 绑定到树视图),您可以修改那里发布的代码以满足您的需求。

  1. 跳过根元素和第一个子元素
  2. TreeNode直接在Nodes-collection中添加一级-s TreeView(因为没有根元素)
  3. TreeNodeAttribute以及为创建Element

例如:

private void Form1_Load ( object sender, EventArgs e )
{
    string xml = "<MainList><number>5</number><first id=\"1\" name=\"test\" /><second/><third/></MainList>";
    XDocument doc = XDocument.Parse ( xml );
    var elements = doc.Root // "MainList"
        .Elements () // Elements inside "MainList"
        .Skip ( 1 ); // Skip first item ("number")
    // Add a TreeNode for each element on first level (inside MainList)
    foreach ( var item in elements )
    {
        // Create first-level-node
        TreeNode node = new TreeNode ( item.Name.LocalName );
        // Create subtree, if necessary
        TreeNode[] nodes = this.GetNodes ( node, item ).ToArray ();
        // Add node with subtree to TreeView
        treeView1.Nodes.AddRange ( nodes );
    }
}

上面的代码使用以下方法从 XML 文档的元素和属性创建 TreeNode:

private IEnumerable<TreeNode> GetNodes ( TreeNode node, XElement element )
{
    List<TreeNode> result = new List<TreeNode> ();
    // First, create TreeNodes for attributes of current element and add them to the result
    if ( element.HasAttributes )
        result.AddRange ( node.AddRange (
            from item in element.Attributes ()
            select new TreeNode ( "[A] " + item.Name.LocalName ) ) );
    // Next, create subtree and add it to the result
    if ( element.HasElements )
        result.AddRange ( node.AddRange ( 
            from item in element.Elements ()
            let tree = new TreeNode ( item.Name.LocalName )
            from newNode in GetNodes ( tree, item )
            select newNode ) );
    // If there aren't any attributes or subelements, return the node that was originally passed in
    if ( result.Count == 0 )
        result.Add ( node );
    // Return the result 
    return result;
}

此外,您需要此扩展方法:

public static class TreeNodeEx
{
    public static IEnumerable<TreeNode> AddRange ( this TreeNode collection, IEnumerable<TreeNode> nodes )
    {
        collection.Nodes.AddRange ( nodes.ToArray () );
        return new[] { collection };
    }
}
于 2012-07-25T10:17:45.693 回答