我正在编写一个简单的任务秒表应用程序,用于我们的EBS系统。
我正在尝试将任务列表序列化为xml并以相同的方式加载它。以下是导出的XML任务列表的示例:
<?xml version="1.0" encoding="utf-8"?>
<Task Task_Name="MainTask" Original_Estimated_Time="10:10:00" Current_Estimated_Time="10:10:00" Elapsed_Time="00:00:00">
<Task Task_Name="Task 2" Original_Estimated_Time="05:00:00" Current_Estimated_Time="05:00:00" Elapsed_Time="00:00:00" />
<Task Task_Name="Task 3" Original_Estimated_Time="15:00:00" Current_Estimated_Time="15:00:00" Elapsed_Time="00:00:00" />
</Task>
当我去导入它时,我创建了一个名为TaskNodes的特殊TreeNode来将信息保存在内存中。但是,子节点没有填充正确的标题字符串(正如您在此屏幕截图中看到的那样):
以下是用于所有XML加载的代码,我看不出根节点和子节点之间的区别:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Title = "Open XML Document";
dlg.Filter = "XML Files (*.xml)|*.xml";
dlg.FileName = Application.StartupPath + "\\..\\..\\example.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 TaskNode(xDoc.DocumentElement.Attributes[0].Value + "", TimeSpan.Parse(xDoc.DocumentElement.Attributes[1].Value + ""), TimeSpan.Parse(xDoc.DocumentElement.Attributes[2].Value + ""), TimeSpan.Parse(xDoc.DocumentElement.Attributes[3].Value + "")));
TaskNode tNode = (TaskNode)treeView1.Nodes[0];
//We make a call to addTreeNode,
//where we'll add all of our nodes
addTaskNode(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 addTaskNode(XmlNode xmlNode, TaskNode taskNode)
{
XmlNode xNode;
TaskNode 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];
taskNode.Nodes.Add(new TaskNode(xNode.Attributes[0].Value + "", TimeSpan.Parse(xNode.Attributes[1].Value + ""), TimeSpan.Parse(xNode.Attributes[2].Value + ""), TimeSpan.Parse(xNode.Attributes[3].Value + "")));
tNode = (TaskNode)taskNode.Nodes[x];
addTaskNode(xNode, tNode);
}
}
else //No children, so add the outer xml (trimming off whitespace)
taskNode.Text = xmlNode.OuterXml.Trim();
}
答案 0 :(得分:0)
else //No children, so add the outer xml (trimming off whitespace)
//taskNode.Text = xmlNode.OuterXml.Trim();
taskNode.Text = xmlNode.InnerXml.Trim();