C# winform 实现 xml文件 显示在treeView下面是 XML 文件:<?xml version="1.0" encoding="utf-8" ?>
<inventory>
<info>
<id>1</id>
<cid>1</cid>
<name>a</name>
</info>
<info>
<id>2</id>
<cid>2</cid>
<name>b</name>
</info>
<info>
<id>3</id>
<cid>3</cid>
<name>c</name>
</info>
<info>
<id>4</id>
<cid>1</cid>
<name>d</name>
</info>
</inventory>
如果节点中的 cid = id ,,把 这个节点的值给它。显示结果:
a
d
b
cwinform 窗体,不是web节点差不多实现了,但就是怎样实现节点中的cid = id ,然后把这个节点值给它呢,郁闷坏了。。
请用递归实现,,能跑起来的,直接送100分。xmlc#winform
<inventory>
<info>
<id>1</id>
<cid>1</cid>
<name>a</name>
</info>
<info>
<id>2</id>
<cid>2</cid>
<name>b</name>
</info>
<info>
<id>3</id>
<cid>3</cid>
<name>c</name>
</info>
<info>
<id>4</id>
<cid>1</cid>
<name>d</name>
</info>
</inventory>
如果节点中的 cid = id ,,把 这个节点的值给它。显示结果:
a
d
b
cwinform 窗体,不是web节点差不多实现了,但就是怎样实现节点中的cid = id ,然后把这个节点值给它呢,郁闷坏了。。
请用递归实现,,能跑起来的,直接送100分。xmlc#winform
private void Form1_Load(object sender, EventArgs e)
{
System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load(Application.StartupPath + "\\XMLFile1.xml");
var els = doc.Root.Descendants("info").ToArray(); LoadTreeNode(els, treeView1.Nodes,""); //加载树节点
}
//递归加载树节点
private void LoadTreeNode(System.Xml.Linq.XElement[] els, TreeNodeCollection Nodes, string id)
{
if (id =="")
{
foreach (System.Xml.Linq.XElement es in els.Where(x => x.Element("id").Value.Equals(x.Element("cid").Value)))
{
TreeNode node = Nodes.Add(es.Element("name").Value);
node.Tag = es.Element("id").Value;
LoadTreeNode(els, node.Nodes, es.Element("id").Value);
}
}
else
{
foreach (System.Xml.Linq.XElement es in els.Where(x => x.Element("cid").Value.Equals(id) && !x.Element("id").Value.Equals(id)))
{
TreeNode node = Nodes.Add(es.Element("name").Value);
node.Tag = es.Element("id").Value;
LoadTreeNode(els, node.Nodes, es.Element("id").Value);
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<Tree>
<TreeNode ID="G1000" Text="aa" SingleClickExpand="true" Icon="Report">
<TreeNode ID="G1001" Text="aa-1" NavigateUrl="aa-1.aspx" Icon="ApplicationFormAdd">
</TreeNode>
<TreeNode ID="G1002" Text="aa-2" NavigateUrl="aa-2.aspx" Icon="ApplicationSideTree">
</TreeNode>
</TreeNode>
</Tree>
我试试...