操作xml,将xml数据显示到treeview的C#代码
效果:
代码:
xmldocument xml = new xmldocument();
private void form1_load(object sender, eventargs e)
{
createxml();
treenode tn = new treenode("魔兽");
treeview1.nodes.add(tn);
xml.load(@"d:\xmlfile.xml");
xmlnode nod = xml.documentelement;
int i = 0;
foreach (xmlnode xn in nod.childnodes)
{
treeview1.topnode.nodes.add(xn.attributes["two"].value);
foreach (xmlnode xn2 in xn.childnodes)
{
treeview1.topnode.nodes[i].nodes.add(xn2.innertext);
}
i++;
}
}
public void createxml()
{
//创建xml文件
xmldeclaration dec = xml.createxmldeclaration("1.0", "utf-8", null);
xml.appendchild(dec);
//添加树形字段
xmlelement one = xml.createelement("one");
xmlelement two = xml.createelement("two");
xmlelement two1 = xml.createelement("two");
xmlelement three = xml.createelement("three");
xmlelement threedl = xml.createelement("three");
xmlelement three1 = xml.createelement("three");
xmlelement three10 = xml.createelement("three");
//添加树形结构关系
xml.appendchild(one);
one.appendchild(two);
one.appendchild(two1);
two.appendchild(three);
two.appendchild(threedl);
two1.appendchild(three1);
two1.appendchild(three10);
//添加属性
two.setattribute("two", "不死");
two1.setattribute("two", "暗夜");
//添加内容
three.innertext = "dk";
threedl.innertext = "dl";
three1.innertext = "dh";
three10.innertext = "wd";
xml.save(@"d:\xmlfile.xml");
}