XML绑定到TreeView控件上

张小巍 2012-05-16 11:25:05
写了个方法,感觉有点笨,而且子节点只是值绑定了进去,节点名称要加进去的话还要循环一层。各位大侠有什么好的方法吗。可以将xml生成dataset直接绑定到treeview上吗?
private void button1_Click(object sender, EventArgs e)
{
string xml1 = @"
<orderVo>
<buid>8270</buid>
<businessCode>SO</businessCode>
<shippingAddress>
<line1>beijing</line1>
<email>mujianbin@hahaha.com.cn</email>
<contactName>baor</contactName>
<mobileNumber1>13612345678</mobileNumber1>
</shippingAddress>
</orderVo>";
this.treeView1.Nodes.Clear();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml1);

XmlNode xmlNode = xmlDoc.DocumentElement;
foreach (XmlNode node in xmlNode.ChildNodes)
{
TreeNode treeNode;
treeNode = this.treeView1.Nodes.Add(node.Name);
foreach (XmlNode subNode in node.ChildNodes)
{
treeNode.Nodes.Add(subNode.InnerText);
}
}
}
...全文
87 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
熙风 2012-05-16
  • 打赏
  • 举报
回复
 private void XmlOperation_Load(object sender, EventArgs e)
{
path = AppDomain.CurrentDomain.BaseDirectory + @"NameList.xml";
xml.Load(path);//加载xml文件
bindTvXml();
}

/// <summary>
/// 绑定TreeView
/// </summary>
private void bindTvXml()
{
for (int i = 0; i < xml.DocumentElement.ChildNodes.Count; i++)
{
XmlNode Xnode = xml.DocumentElement.ChildNodes[i];
TreeNode node = new TreeNode();
node.Text = Xnode.Attributes["name"].Value;
node.Tag = Xnode;
bindChildNode(node, Xnode);//绑定子节点
TvXml.Nodes.Add(node);
TvXml.HideSelection = false;
}
}

/// <summary>
/// 递归绑定子节点
/// </summary>
/// <param name="node"></param>
/// <param name="xml"></param>
private void bindChildNode(TreeNode node, XmlNode xml)
{
for (int i = 0; i < xml.ChildNodes.Count; i++)
{
TreeNode Childnode = new TreeNode();
XmlNode ChildXml = xml.ChildNodes[i];
Childnode.Text = ChildXml.Value;
Childnode.Name = "1";
Childnode.Tag = xml.ChildNodes[i];
if (ChildXml.HasChildNodes)
{
if (ChildXml.ChildNodes[0].NodeType == XmlNodeType.Text)
Childnode.Text = ChildXml.ChildNodes[0].InnerText;
else
bindChildNode(Childnode, ChildXml);
}
node.Nodes.Add(Childnode);
}

}

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧