XML解析、使用TreeView呈现效果

首先用到TXMLDocument控件;

Memo来显示XML文件,

TreeView来呈现元素;

源代码:

 

Procedure TForm2.Button1Click(Sender: TObject);
Begin
    XMLDocument1.LoadFromFile('E:\template1.xml');
    Memo1.Font.Size :=15;
    Memo1.Align := TAlignLayout.alLeft;
    Memo1.Lines := XMLDocument1.XML; {查看}
End;

Procedure TForm2.Button2Click(Sender: TObject);
Var
    nodeList: IXMLNodeList;
    node: IXMLNode;
    num,i: Integer;
    Item: TTreeViewItem;
    Item2 : TTreeViewItem;
    Item3 : TTreeViewItem;
Begin
    TreeView1.Align := TAlignLayout.alRight;
    TreeView1.AlternatingRowBackground := True;

    Item := TTreeviewItem.Create(Self);

//根元素
    Item.Parent := TreeView1;
    Item.Text := XMLDocument1.DocumentElement.Attributes['备注'];
    Item.Font.Size :=22;
//子节点
    nodeList := XMLDocument1.DocumentElement.ChildNodes;
    num := nodeList.Count;
    For i := 0 To num - 1 Do
    Begin
        Item2 := TTreeviewItem.Create(Self);
        Item2.Parent := Item;
        Item2.Text := nodeList[i].Attributes['职务'];
//子元素的属性
        Item3 := TTreeviewItem.Create(Self);
        Item3.Parent := Item2;
        Item3.Text := nodeList[i].ChildValues['姓名'];
        Item3 := TTreeviewItem.Create(Self);
        Item3.Parent := Item2;
        Item3.Text := nodeList[i].ChildValues['性别'];
        Item3 := TTreeviewItem.Create(Self);
        Item3.Parent := Item2;
        Item3.Text := nodeList[i].ChildValues['年龄'];
    End;
End;
 

 

 这是测试的效果图;

 

 

 

 

你可能感兴趣的:(treeview)