树视图中未显示IP地址。
这是我的xml COde:
<?xml version="1.0" standalone="yes"?>
<config>
<service name="router">
<ip_address>10.0.3.1</ip_address>
<action>active</action>
</service>
<service name="sname2">
<ip_address>10.0.3.2</ip_address>
<weight>4</weight>
<action>active</action>
</service>
<service name="sname3">
<ip_address>10.0.3.3</ip_address>
<weight>5</weight>
<protocol>udp</protocol>
<action>suspend</action>
</service>
<service name="nick">
<ip_address>10.0.3.93</ip_address>
<action>active</action>
</service>
<owner name="test">
<content name="rule">
<vip_address>10.0.3.100</vip_address>
<protocol>udp</protocol>
<port>8080</port>
<add_service>nick</add_service>
<action>active</action>
</content>
</owner>
</config>
在treeview中,IP地址没有显示,我从xml文件加载,所以这是我的代码和屏幕,有人能知道这个问题吗?
using System.Xml;
using System.IO;
namespace howto_load_treeview_from_xml
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string filename = Application.StartupPath;
filename = System.IO.Path.Combine(filename, "..\\..");
filename = Path.GetFullPath(filename) + "\\test.xml";
LoadTreeViewFromXmlFile(filename, trvItems);
}
// Load a TreeView control from an XML file.
private void LoadTreeViewFromXmlFile(string filename, TreeView trv)
{
// Load the XML document.
XmlDocument xml_doc = new XmlDocument();
xml_doc.Load(filename);
// Add the root node's children to the TreeView.
trv.Nodes.Clear();
AddTreeViewChildNodes(trv.Nodes, xml_doc.DocumentElement);
}
// Add the children of this XML node
// to this child nodes collection.
private void AddTreeViewChildNodes(TreeNodeCollection parent_nodes, XmlNode xml_node)
{
foreach (XmlNode child_node in xml_node.ChildNodes)
{
// Make the new TreeView node.
TreeNode new_node = parent_nodes.Add(child_node.Name);
// Recursively make this node's descendants.
AddTreeViewChildNodes(new_node.Nodes, child_node);
// If this is a leaf node, make sure it's visible.
if (new_node.Nodes.Count == 0) new_node.EnsureVisible();
}
}
}
}
答案 0 :(得分:2)
由于您使用文本节点的#text
属性作为树视图节点名称,因此会在树视图中显示那些Name
。要获取显示的文本节点的实际值,请改用Value
属性,类似这样的内容(未经测试的代码):
private void AddTreeViewChildNodes(TreeNodeCollection parent_nodes, XmlNode xml_node)
{
foreach (XmlNode child_node in xml_node.ChildNodes)
{
var isTextNode = child_node.NodeType == XmlNodeType.Text;
var treeNodeName = isTextNode ? child_node.Value : child_node.Name;
// Make the new TreeView node.
TreeNode new_node = parent_nodes.Add(treeNodeName);
// Recursively make this node's descendants.
AddTreeViewChildNodes(new_node.Nodes, child_node);
// If this is a leaf node, make sure it's visible.
if(new_node.Nodes.Count == 0) new_node.EnsureVisible();
}
}