C#中将Xml文件在treeview中动态加载(xml中的是数据是可变的)
<Cinema><Channlname="非常完美"><Time>9:00</Time><Time>13:00</Time></Channl><Channlname="风...
<Cinema>
<Channl name="非常完美">
<Time>9:00</Time>
<Time>13:00</Time>
</Channl>
<Channl name="风声">
<Time>10:00</Time>
<Time>14:00</Time>
</Channl>
<Channl name="窃听风云">
<Time>9:00</Time>
</Channl>
</Cinema>
显示的样式:非常完美
>9:00
>13:00
风声
>10:00
>14:00 ...
求代码如何写? 展开
<Channl name="非常完美">
<Time>9:00</Time>
<Time>13:00</Time>
</Channl>
<Channl name="风声">
<Time>10:00</Time>
<Time>14:00</Time>
</Channl>
<Channl name="窃听风云">
<Time>9:00</Time>
</Channl>
</Cinema>
显示的样式:非常完美
>9:00
>13:00
风声
>10:00
>14:00 ...
求代码如何写? 展开
展开全部
public Form1()
{
InitializeComponent();
string path = @"c:\test.xml";
InitialTreeView(treeView1.Nodes, path);
}
private void InitialTreeView(TreeNodeCollection nodes, string fileName)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
TreeNode parentNode = new TreeNode();
parentNode.Text = doc.DocumentElement.Name;
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
XmlElement xe = node as XmlElement;
TreeNode newNode = new TreeNode();
foreach (XmlAttribute attr in xe.Attributes)
{
newNode.Text = attr.Value;
}
//调用递归函数
SearchXmlDoc(node, newNode);
//添加子节点
parentNode.Nodes.Add(newNode);
}
nodes.Add(parentNode);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
/// 递归遍历xml,为treeview绑定数据
private static void SearchXmlDoc(XmlNode xmlNode, TreeNode treeNode)
{
if (xmlNode.ChildNodes.Count == 0)
{
return;
}
else
{
foreach (XmlNode node in xmlNode.ChildNodes)
{
try
{
if (node.NodeType == XmlNodeType.Element)
{
string value = node.InnerText;
TreeNode newNode = new TreeNode();
newNode.Text = value;
SearchXmlDoc(node, newNode);
treeNode.Nodes.Add(newNode);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
{
InitializeComponent();
string path = @"c:\test.xml";
InitialTreeView(treeView1.Nodes, path);
}
private void InitialTreeView(TreeNodeCollection nodes, string fileName)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
TreeNode parentNode = new TreeNode();
parentNode.Text = doc.DocumentElement.Name;
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
XmlElement xe = node as XmlElement;
TreeNode newNode = new TreeNode();
foreach (XmlAttribute attr in xe.Attributes)
{
newNode.Text = attr.Value;
}
//调用递归函数
SearchXmlDoc(node, newNode);
//添加子节点
parentNode.Nodes.Add(newNode);
}
nodes.Add(parentNode);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
/// 递归遍历xml,为treeview绑定数据
private static void SearchXmlDoc(XmlNode xmlNode, TreeNode treeNode)
{
if (xmlNode.ChildNodes.Count == 0)
{
return;
}
else
{
foreach (XmlNode node in xmlNode.ChildNodes)
{
try
{
if (node.NodeType == XmlNodeType.Element)
{
string value = node.InnerText;
TreeNode newNode = new TreeNode();
newNode.Text = value;
SearchXmlDoc(node, newNode);
treeNode.Nodes.Add(newNode);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询