我在鏈接「http://msdn.microsoft.com/en-us/library/」中提供了一個名爲「books.xml」的xml文件窗戶/桌面/ ms762271(v = vs.85)的.aspx」。我的要求是僅將xml信息中的<title>
作爲樹視圖中的節點來消除。但是,當我做了下面的代碼,它顯示所有的價值作爲節點像「目錄」作爲根節點,作爲父節點作爲節點,然後作者,標題,流派等節點,但我只需要根節點目錄和標題作爲節點,甚至不是書。任何機構可以引導我,我需要什麼樣的修改在exisitng邏輯用於顯示標題來做爲節點如何從xml文件中過濾數據以僅顯示在樹視圖中選中的節點
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open XML document";
dlg.Filter = "XML Files (*.xml)|*.xml";
dlg.FileName = Application.StartupPath + "\\..\\..\\Sample.xml";
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
//Just a good practice -- change the cursor to a
//wait cursor while the nodes populate
this.Cursor = Cursors.WaitCursor;
//First, we'll load the Xml document
XmlDocument xDoc = new XmlDocument();
xDoc.Load(dlg.FileName);
//Now, clear out the treeview,
//and add the first (root) node
treeView1.Nodes.Clear();
treeView1.Nodes.Add(new
TreeNode(xDoc.DocumentElement.Name));
TreeNode tNode = new TreeNode();
tNode = (TreeNode)treeView1.Nodes[0];
//We make a call to addTreeNode,
//where we'll add all of our nodes
addTreeNode(xDoc.DocumentElement, tNode);
//Expand the treeview to show all nodes
treeView1.ExpandAll();
}
catch (XmlException xExc)
//Exception is thrown is there is an error in the Xml
{
MessageBox.Show(xExc.Message);
}
catch (Exception ex) //General exception
{
MessageBox.Show(ex.Message);
}
finally
{
this.Cursor = Cursors.Default; //Change the cursor back
}
}}
//This function is called recursively until all nodes are loaded
private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList xNodeList;
if (xmlNode.HasChildNodes) //The current node has children
{
xNodeList = xmlNode.ChildNodes;
for (int x = 0; x <= xNodeList.Count - 1; x++)
//Loop through the child nodes
{
xNode = xmlNode.ChildNodes[x];
treeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = treeNode.Nodes[x];
addTreeNode(xNode, tNode);
}
}
else //No children, so add the outer xml (trimming off whitespace)
treeNode.Text = xmlNode.OuterXml.Trim();
}
嘗試[linqtoXML(http://msdn.microsoft.com/en-us/library/bb387098.aspx) – pylover 2012-03-26 11:09:22
如果有人重寫我的exisitng編碼,這將有助於 – michale 2012-03-26 11:13:48