如何把xml文件里的元素、子元素等在treeview中显示出来?
<?xmlversion="1.0"encoding="utf-8"?><bookstore><bookgenre="fantasy1"ISBN="2-3631-1"><...
<?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> 展开
<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> 展开
2个回答
展开全部
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 (xmlLeaf is System.Xml.XmlComment) //如果当前节点是注释,跳过
continue;
TreeNode treeLeaf = new TreeNode();
treeLeaf.Text = xmlLeaf.InnerText; //设置结点的显示文字
treeRoot.ChildNodes.Add(treeLeaf);
}
}
}
{
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 (xmlLeaf is System.Xml.XmlComment) //如果当前节点是注释,跳过
continue;
TreeNode treeLeaf = new TreeNode();
treeLeaf.Text = xmlLeaf.InnerText; //设置结点的显示文字
treeRoot.ChildNodes.Add(treeLeaf);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询