如何把xml文件里的元素、子元素等在treeview中显示出来?

来源:百度知道 编辑:UC知道 时间:2024/05/22 21:54:05
<?xml version="1.0" encoding="utf-8"?>
<bookstore>
<book genre="fantasy1" ISBN="2-3631-1">
<title>title1</title>
<author>author1</author>
<price>5.5</price>
</book>
<book genre="fantasy2" ISBN="2-3631-2">
<title>title2</title>
<author>author2</author>
<price>6.6</price>
</book>
<book genre="fantasy3" ISBN="2-3631-3">
<title>title3</title>
<author>author3</author>
<price>7.7</price>
</book>
</bookstore>

protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xml = new XmlDocument();
xml.Load(Server.MapPath("XML文件名.xml"));

XmlNode xmlRoot = xml.ChildNodes[1];//得到XML的根结点,ChildNodes[0]指向<?xml version="1.0" encoding="utf-8"?>

for (int i = 0; i < xmlRoot.ChildNodes.Count; i++)
{
XmlNode xmlChd = xmlRoot.ChildNodes[i];
if (xmlChd is System.Xml.XmlComment) //如果当前节点是注释,跳过
continue;

//添加树的根结点
TreeNode treeRoot = new TreeNode();
treeRoot.Text = xmlChd.Attributes["genre"].Value; //设置结点的显示文字
treeRoot.Expanded = true; //设置结点的初始状态为展开
treeRoot.SelectAction = TreeNodeSelectAction.Expand;//设置结点的点击操作为展开或收拢结点
TreeView1.Nodes.Add(treeRoot);

//添加当前根结点的子结点
for (int j = 0; j < xmlChd.ChildNodes.Count; j++)
{
XmlNode xmlLeaf = xmlChd.ChildNodes[j];
if (x