Jag har en XML-fil som är specad enligt följande:
<?xml version="1.0" encoding="UTF-8" ?>
<prislista gid="Juni 2005" expire="2005-12-31">
<grupp gid="1">
<grupp gid="10">
</grupp>
<grupp gid="20">
</grupp>
<grupp gid="30">
</grupp>
<grupp gid="40">
</grupp>
<grupp gid="50">
</grupp>
<grupp gid="60">
</grupp>
</grupp>
<grupp gid="2">
<grupp gid="10">
</grupp>
<grupp gid="20">
</grupp>
<grupp gid="30">
</grupp>
<grupp gid="40">
</grupp>
<grupp gid="50">
</grupp>
<grupp gid="60">
</grupp>
</grupp>
</prislista>
Koden för att parsa XML-filen är följande:
private void LoadXML()
{
try
{
// SECTION 1. Create a DOM Document and load the XML data into it.
XmlDocument dom = new XmlDocument();
dom.Load("prislista2.xml");
// SECTION 2. Initialize the TreeView control.
treeView1.Nodes.Clear();
treeView1.Nodes.Add(new TreeNode(dom.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = treeView1.Nodes[0];
// SECTION 3. Populate the TreeView with the DOM nodes.
AddNode(dom.DocumentElement, tNode);
treeView1.ExpandAll();
}
catch(XmlException xmlEx)
{
MessageBox.Show(xmlEx.Message);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList nodeList;
int i;
// Loop through the XML nodes until the leaf is reached.
// Add the nodes to the TreeView during the looping process.
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for(i = 0; i<=nodeList.Count - 1; i++)
{
xNode = inXmlNode.ChildNodes[i];
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(xNode, tNode);
}
}
else
{
// Here you need to pull the data from the XmlNode based on the
// type of node, whether attribute values are required, and so forth.
inTreeNode.Text = (inXmlNode.OuterXml).Trim();
}
}
Hur ska jag göra för att kunna begränsa min parsning? Jag vill t.ex. kunna ange gid=2 och då ska grupperna under gid=2 hämtas och läggas upp i min TreeView (samt ev. undergrupper)