Filtering XML tags when loading into a tree
I am trying to load an XML file into a tree control, edit it and save it back in a different XML format.
<MyConfig>
<description>
<![CDATA[Add All config data]]>
</description>
<group name="Server">
<description>
<![CDATA[Server info]]>
</description>
<parameter name="Host" type="string">
<description>
<![CDATA[Host Name]]>
</description>
<value>cccc.ac.lk</value>
</parameter>
<parameter name="Port" type="integer">
<description>
<![CDATA[port no]]>
</description>
<range>0-65536</range>
<value>47110</value>
</parameter>
</group>
</MyConfig>
I am using the following method to load XML data
private void populateTreeControl(System.Xml.XmlNode document,
System.Windows.Forms.TreeNodeCollection nodes)
{
foreach (System.Xml.XmlNode node in document.ChildNodes)
{
string text = (node.Value != null ? node.Value :
(node.Attributes != null && node.Attributes.Count > 0) ?
node.Attributes[0].Value : node.Name);
TreeNode new_child = new TreeNode(text);
nodes.Add(new_child);
populateTreeControl(node, new_child.Nodes);
}
}
Now I want to filter some nodes and load them into a tree structure. As an example, it is useless for me to load description tags etc. In the above case. I just want to create a tree using MyConfig -> Group -> Server ---> Host and MyConfig -> Group -> Server ---> Port
How do I change the populateTreeControl () method to get this?
0
a source to share
1 answer
private void populateTreeControl(
System.Xml.Node context,
System.Windows.Forms.TreeNodeCollection treeNodes,
List<string> xpath,
int depth
)
{
if (xpath.Count > depth) {
foreach (System.Xml.XmlNode xmlNode in context.SelectNodes(xpath[depth]))
{
string text = "";
if (xmlNode.Value != null)
text = xmlNode.Value;
else if (xmlNode.Attributes.Count > 0)
text = xmlNode.Attributes[0].Value;
else
text = xmlNode.Name;
TreeNode new_child = new TreeNode(text);
treeNodes.Add(new_child);
populateTreeControl(xmlNode, new_child.Nodes, xpath, depth + 1);
}
}
}
call
List<string> xpath = new List<string>();
xpath.Add("/MyConfig/group/[@name='Server']");
xpath.Add("parameter[@name='Host' or @name='Port']");
populateTreeControl(xmlDoc, tree.Nodes, xpath, 0);
+1
a source to share