C#关于xml文件和TreeView之间的转换解析

主窗体:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using celfras;
using System.Threading;

namespace Civet
{
    public partial class ParseXmlFilesForm : Form
    {
        public static WirelessCharge myCelfras = new WirelessCharge();
        #region 变量申明
        private string xmlFilePath;
        DataTable dt = new DataTable();
        private TreeViewUtils tvUtil;
        private Dictionary<int, TreeNode> dic = new Dictionary<int, TreeNode>();
        private Boolean bState = false;
        private string sLogName = null;

        private bool isTesterInit = false;
        private bool isDUTInit = false;
        private bool isCWQ1100CalTest = false;
        private bool isCWQ1100FunctionTest = false;
        private StringBuilder sFTLogs = new StringBuilder();
        

        #endregion
        public ParseXmlFilesForm()
        {
            InitializeComponent();
            dt.Columns.Add("InputName");
            dt.Columns.Add("InputValue");
            dt.Columns.Add("OutputName");
            dt.Columns.Add("OutputValue");
            dataGridView1.DataSource = dt;
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            btnRun.Enabled = false;
            btnSave.Enabled = false;

            contextMenuStrip1.Items.Add("清除内容");

            treeView1.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseDoubleClick); 
            dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
            treeView1.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(treeView1_AfterCheck);
            contextMenuStrip1.ItemClicked += new ToolStripItemClickedEventHandler(contextMenuStrip1_StripItemClick);

            richTextBox1.ContextMenuStrip = this.contextMenuStrip1;

            tvUtil = new TreeViewUtils(treeView1,richTextBox1);
            tvUtil.InitTreeView();

            //Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void AppendText(string Text)
        {
            this.Invoke(new MethodInvoker(delegate ()
            {
                richTextBox1.Text += Text;
            }));
        }

        //更新dataGridView中output值
        private void UpdataDataGridView(Dictionary<string,string> dic,TreeNode node) {
            this.Invoke(new MethodInvoker(delegate () {
                foreach (KeyValuePair<string,string> kvPair in dic) {
                    for (int i = 0; i < node.Nodes[2].Nodes.Count; i++)
                    {
                        string cellText = dataGridView1.Rows[i].Cells[2].Value.ToString();
                        if (cellText == kvPair.Key)
                        {
                            dataGridView1.Rows[i].Cells[3].Value = kvPair.Value;
                            break;
                        }
                    }
                }      
            }));
        }


        #region click event
        //打开xml文档,解析成TreeView显示
        private void btn_openFile_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "XML文件|*.xml";
            if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            else
            {
                xmlFilePath = System.IO.Path.GetFullPath(openFileDialog1.FileName);
                if (!tvUtil.listPaths.Contains(xmlFilePath))
                {
                    tvUtil.Xml2Tree(xmlFilePath);
                    comboBox1.Text = xmlFilePath;
                    comboBox1.Items.Add(xmlFilePath);
                    btnSave.Enabled = true;
                    btnRun.Enabled = true;
                }
                else {
                    MessageBox.Show("你已经打开该xml文件!","提示!");
                }
            }
        }

        //xml文档修改之后的保存操作
        private void btnSave_Click(object sender, EventArgs e)
        {
            tvUtil.SaveTreeView2XML();
            MessageBox.Show("保存成功!");
        }
        //清除窗口所有显示信息
        private void btnClear_Click(object sender, EventArgs e)
        {
            comboBox1.Text = "";
            richTextBox1.Clear();
            treeView1.Nodes.Clear();
            dt.Clear();
            tvUtil.listPaths.Clear();
            dic.Clear();

            btnRun.Text = "Run";
        }

        private BackgroundWorker RunTestWork = null;
        //测试操作
        private void btnRun_Click(object sender, EventArgs e)
        {
            dic = dic.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);

            if (btnRun.Text == "Run")
            {
                myCelfras.CFS_LOG_Init(ref sLogName);
                myCelfras.CFS_CSV_Init(ref sLogName);

                RunTestWork = new BackgroundWorker()
                {
                    WorkerSupportsCancellation = true,
                };
                RunTestWork.DoWork += RunTestWork_DoWork;
                RunTestWork.RunWorkerAsync();
                btnRun.Text = "Pause";
            }
            else {
                if (btnRun.Text == "Pause") {
                    manualReset.Reset();
                    btnRun.Text = "Continue";
                }
                else if (btnRun.Text == "Continue") {
                    manualReset.Set();
                    btnRun.Text = "Pause";
                }
            }
           
        }
        private ManualResetEvent manualReset = new ManualResetEvent(true);
        private void RunTestWork_DoWork(object sender, DoWorkEventArgs e)
        {
            InvokeDll(e);
            
            MessageBox.Show("测试结束!", "提示!");
            this.Invoke(new MethodInvoker(delegate ()
            {
                btnRun.Text = "Run";
            }));

            foreach (TreeNode node in treeView1.Nodes[0].Nodes)
            {
                node.BackColor = Color.White;
            }
        }
     
        //将TreeView中的节点信息显示到DataGridView中显示
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            dt.Clear();
            TreeNode node = treeView1.SelectedNode;
            if ("testNode".Equals(node.Tag))
            {
                tvUtil.AddNode2GridView(node,dt);
            }
        }
        //TreeView中node check之后的操作
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            tvUtil.AddNode2Dic(e.Node,dic);
        }
        //下拉选择
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tvUtil.listPaths.Contains(comboBox1.Text)) {
                MessageBox.Show("Tr1eeView中已经加载该xml文件!", "提示!");
                return;
            }
            tvUtil.Xml2Tree(comboBox1.Text);
        }
        //设置TreeView节点双击可修改内容
        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point clickPoint = new Point(e.X, e.Y);
                TreeNode currentNode = treeView1.GetNodeAt(clickPoint);
                if (currentNode != null && currentNode.Nodes.Count == 0)
                {
                    treeView1.SelectedNode = currentNode;
                    treeView1.LabelEdit = true;
                    treeView1.SelectedNode.BeginEdit();
                }
            }
        }

        //dataGridView中单元格内容修改的事件处理
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex % 2 != 0)
            {
                string cellValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                string cellName = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex - 1].Value.ToString();

                tvUtil.CircleNode(cellName, cellValue, treeView1.Nodes);
            }
        }

        //richTextBox增加内容的时候,滚动条自动滚动到最底部
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (richTextBox1.TextLength > 0)
            {
                richTextBox1.Select(richTextBox1.TextLength, 0);
                //richTextBox_TestLog.Focus();
                richTextBox1.ScrollToCaret();
            }
        }

        //在RichTextBox控件上右击,选择清除,清除控件显示内容
        private void contextMenuStrip1_StripItemClick(object sender, ToolStripItemClickedEventArgs e)
        {
            //MessageBox.Show(e.ClickedItem.ToString());
            switch (e.ClickedItem.ToString())
            {
                case "清除内容":
                    richTextBox1.Clear();
                    break;
            }
        }
        #endregion

        private Dictionary<string, string> dicOutput = null;
        #region connect device
        public void InvokeDll(DoWorkEventArgs e)
        {
            dicOutput = new Dictionary<string, string>();
            try
            {
                foreach (KeyValuePair<int, TreeNode> kvPair in dic)
                {
                    if (RunTestWork.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    TreeNode node = kvPair.Value;
                    node.BackColor = Color.DarkOrange;
                    string nodeText = node.Text.Split(']')[1].Trim();

                    this.Invoke(new MethodInvoker(delegate ()
                    {
                        dt.Clear();
                        tvUtil.AddNode2GridView(node, dt);
                    }));

                    switch (nodeText)
                    {
                        case "Init_DUT":
                            AppendText("\n-----------Init_DUT-------------");
                            bState = RunInitDut(node);
                            bState = true;
                            if (bState == false)
                                throw new Exception("run_Init_DUT()");
                            Thread.Sleep(2000);
                            break;
                        case "Init_Tester_Cal":
                            AppendText("\n------------Init_Tester_Cal------------");
                            bState = run_Init_Tester_Cal(node);
                            bState = true;
                            if (bState == false)
                                throw new Exception("Init_Tester_Cal()");
                            Thread.Sleep(1000);
                            break;
                        case "Init_Tester_FT":
                            Thread.Sleep(2000);
                            AppendText("\n------------Init_Tester_FT------------");
                            bState = run_Init_Tester_FT(node);
                            bState = true;
                            if (bState == false)
                                throw new Exception("Init_Tester_FT()");
                            break;
                        case "Init_Tester_FT2":
                            Thread.Sleep(2000);
                            AppendText("\n------------Init_Tester_FT2------------");
                            bState = run_Init_Tester_FT2(node);
                            bState = true;
                            if (bState == false)
                                throw new Exception("Init_Tester_FT()");
                            break;
                        case "BGRVoltageCalibration":
                            AppendText("\n------------BGRVoltageCalibration------------");
                            //isCWQ1100CalTest = true;
                            bState = Run_BGR_Voltage_Calibration(node);
                            if (bState == false)
                                throw new Exception("run_BGRVoltageCal()");
                            break;
                        case "OSCFrequencyCalibration":
                            AppendText("\n ------------OSCFrequencyTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = Run_OSC_Frequenty_Calibration(node);
                            if (bState == false)
                                throw new Exception("run_OSCFrequencyTest()");
                            break;
                        case "VOUTVoltageCalibration":
                            AppendText("\n ------------VOUTVoltageCalibration------------");
                            //isCWQ1100CalTest = true;
                            bState = Run_VOUT_Calibration(node); 
                            if (bState == false)
                                throw new Exception("run_VOUTVoltageCal()");
                            break;
                        case "ADCIOUTCalibration":
                            AppendText("\n------------ADCIOUTCalibration------------");
                            //isCWQ1100CalTest = true;
                            bState = Run_ADC_IOUT_Calibration(node);
                            if (bState == false)
                                throw new Exception("run_ADCIOUTCal()");
                            break;
                        case "OTPWrite":
                            AppendText("\n------------OTPWrite------------");
                            bState = Run_OTP_Write(node);
                            if (bState == false)
                                throw new Exception("run_OTPWrite()");
                            AppendText("测试结束写LOG");
                            break;
                        case "BGRVoltageTest":
                            //isCWQ1100FunctionTest = true;
                            AppendText("\n ------------BGRVoltageTest------------");
                            bState = Run_BGR_Voltage_Test(node);
                            if (bState == false)
                                throw new Exception("run_BGRVoltageTest()");
                            break;
                        case "OSCFrequencyTest":
                            AppendText("\n------------OSCFrequencyTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = Run_OSC_Frequency_Test(node);
                            if (bState == false)
                                throw new Exception("run_OSCFrequencyTest()");
                            break;
                        case "LDOVoltageTest":
                            AppendText("\n------------LDOVoltageTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = Run_LDOVoltageTest(node);
                            if (bState == false)
                                throw new Exception("run_LDOVoltageTest()");
                            break;
                        case "ADCTest":
                            AppendText("\n------------ADCTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_ADCTest(node);
                            if (bState == false)
                                throw new Exception("run_LDOVoltageTest()");
                            break;
                        case "CurrentSensorTest":
                            AppendText("\n------------CurrentSensorTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_CurrentSensorTest(node);
                            if (bState == false)
                                throw new Exception("run_CurrentSensorTest()");
                            break;
                        case "OCLTest":
                            AppendText("\n------------OCLTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_OCLTest(node);
                            if (bState == false)
                                throw new Exception("run_OCLTest()");
                            break;
                        case "TestPortTest":
                            AppendText("\n------------TestPortTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_TestPortTest(node);
                            if (bState == false)
                                throw new Exception("run_OCLTest()");
                            break;
                        case "FunctionTest1":
                            AppendText("\n------------FunctionTest1------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_FunctionTest1(node);
                            if (bState == false)
                                throw new Exception("run_FunctionTest1()");
                            break;
                        case "FunctionTest2":
                            AppendText("\n------------FunctionTest2------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_FunctionTest2(node);
                            if (bState == false)
                                throw new Exception("run_FunctionTest2()");
                            break;
                        case "LDOVDDTest":
                            AppendText("\n------------LDOVDDTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_LDOVDDTest(node);
                            if (bState == false)
                                throw new Exception("run_LDOVDDTest()");
                            break;
                        case "ENBTest":
                            AppendText("\n------------ENBTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_ENBTest(node);
                            if (bState == false)
                                throw new Exception("run_ENBTest()");
                            break;
                        case "OVPTest":
                            AppendText("\n------------OVPTest------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_OVPTest(node);
                            if (bState == false)
                                throw new Exception("run_OVPTest()");
                            break;
                        //CloseTester
                        case "CloseTester":
                            AppendText("\n------------CloseTester------------");
                            //isCWQ1100FunctionTest = true;
                            bState = run_CloseTester(node);
                            if (bState == false)
                                throw new Exception("run_CloseTester()");
                            break;
                        default:
                            AppendText("\n" + string.Format("------------{0}------------", nodeText));
                            AppendText("\n------------TBD------------");
                            break;
                    }
                    manualReset.WaitOne();
                    node.BackColor = Color.DarkGray;                   
                }
                MessageBox.Show("Press any Key to another DUT test..");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示!");
            }
            finally
            {
                if (isCWQ1100CalTest == true)
                {
                    myCelfras.CFS_TM_CALFinish();
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    Console.WriteLine(sFTLogs);

                }
                if (isCWQ1100FunctionTest)
                {
                    myCelfras.CFS_FT_RUNSummary();
                }
                myCelfras.CFS_Term();
                isCWQ1100CalTest = false;
                isCWQ1100FunctionTest = false;
            }
        }  

        #region init dut 、pwr、osc
        private Boolean RunInitDut(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[2].Text + "=" + node.Nodes[1].Nodes[2].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[3].Text + "=" + node.Nodes[1].Nodes[3].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[4].Text + "=" + node.Nodes[1].Nodes[4].Nodes[0].Text);
                    System.Threading.Thread.Sleep(100);
                    bool bState = false;
#if true
                    if (isDUTInit == false)
                    {

                        bState = myCelfras.CFS_CWQ1100_I2CInit(0x24, 0.15);
                        if (bState == false)
                            throw new Exception("CFS_CWQ1100_I2CInit()");
                        isDUTInit = true;
                    }
                    AppendText("\n CWQ1100 Init OK..");
#endif

                    bState = myCelfras.CFS_CWQ1100_ISOK();
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    //Console.WriteLine(sFTLogs);
                    if (bState == false)
                        throw new Exception("CFS_CWQ1100_ISOK()");

                    if (isCWQ1100CalTest == true)
                    {
                        bState = myCelfras.CFS_CWQ1100_OTP_Before();
                        if (bState)
                        {
                            AppendText("\n This chip is not otp");
                        }
                        else
                            AppendText("\n [ERR]This chip is otp");
                        //throw new Exception("CFS_CWQ1100_OTP_Before()");
                    }
                    return true;
                }
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                return false;
            }
        }

        private bool run_Init_Tester_Cal(TreeNode node)
        {
            try
            {
                string sPowerSupply1 = null;
                string sPowerSupply2 = null;
                string sOscilloScope = null;
                string sElectonicLoad = null;
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")) && (isTesterInit == false))
                {
                    isCWQ1100CalTest = true;
                    isTesterInit = false;//init tester only once
                                         //step1 get tester data
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[2].Text + "=" + node.Nodes[1].Nodes[2].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[3].Text + "=" + node.Nodes[1].Nodes[3].Nodes[0].Text);
                    
                    if (node.Nodes[1].Nodes[0].Text != "PowerSupply1")
                        throw new Exception("PowerSupply1 Address set error");
                    else
                        sPowerSupply1 = node.Nodes[1].Nodes[0].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[1].Text != "PowerSupply2")
                        throw new Exception("PowerSupply2 Address set error");
                    else
                        sPowerSupply2 = node.Nodes[1].Nodes[1].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[2].Text != "OscilloScope")
                        throw new Exception("OscilloScope Address set error");
                    else
                        sOscilloScope = node.Nodes[1].Nodes[2].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[3].Text != "ElectonicLoad")
                        throw new Exception("ElectonicLoad Address set error");
                    else
                        sElectonicLoad = node.Nodes[1].Nodes[3].Nodes[0].Text;
                    //step1 连线方式说明
                    AppendText("\n---------------------------------------------------------------------");
                    AppendText("\n Cal Test 连线方式说明");
                    AppendText("\n PowerSupply1 VRECT 5.5V");
                    AppendText("\n PowerSupply2 VPP 3.3V");
                    AppendText("\n OscilloScope CH1:ANA_TEST// CH2:DIG_TEST// CH3:VOUT //CH4:VRECT");
                    AppendText("\n ElectonicLoad VOUT default off");

                    //step2 connect osc
                    bool bState = myCelfras.CFS_OSC_Init(sOscilloScope);
                    if (bState == false)
                        throw new Exception("CFS_OSC_Init()" + sOscilloScope);

                    //step3 connect powersupply2 vpp default is 3.3V
                    bState = myCelfras.CFS_PWR2_Init(sPowerSupply2);
                    if (bState == false)
                        throw new Exception("CFS_PWR_Init()" + sPowerSupply2);
                    myCelfras.CFS_PWR2_OnOff(false);
                    myCelfras.CFS_PWR2_SetVoltage(3.0);
                    myCelfras.CFS_PWR2_SetCurrent(2.0);
                    myCelfras.CFS_PWR2_OnOff(true);
                    System.Threading.Thread.Sleep(1000);

                    //step4 connect powersupply1 VRECT
                    bState = myCelfras.CFS_PWR_Init(sPowerSupply1);
                    if (bState == false)
                        throw new Exception("CFS_PWR_Init()" + sPowerSupply1);
                    myCelfras.CFS_PWR_OnOff(false);
                    myCelfras.CFS_PWR_SetVoltage(5.5);
                    myCelfras.CFS_PWR_SetCurrent(2.0);
                    myCelfras.CFS_PWR_OnOff(true);
                    //step3 check osc channel 4 is 5.5V
                    double dVrect = 0.0;
                    myCelfras.CFS_OSC_SendCmd(4);
                    myCelfras.CFS_OSC_GetVoltage(4, ref dVrect);
                    AppendText("\n Check Vrect Voltage = " + dVrect);
                    if ((dVrect <= 5.6) && (dVrect >= 5.4))
                        AppendText("\n Vrect Voltage is ok");
                    else
                        throw new Exception("Vrect Voltage is wrong,check powersupply");
                    System.Threading.Thread.Sleep(1000);

                    //step5 connect load
                    bState = myCelfras.CFS_ELD_Init(sElectonicLoad);
                    if (bState == false)
                        throw new Exception("CFS_ELD_Init()" + sElectonicLoad);
                    myCelfras.CFS_ELD_OnOff(false);
                    myCelfras.CFS_ELD_SetCurrent(1.0);
                    myCelfras.CFS_ELD_SetModeCC();
                    
                    return true;
                }
                return true;
            }catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                return false;
            }
        }

        private bool run_Init_Tester_FT(TreeNode node)
        {
            try
            {
                string sPowerSupply1 = null;
                string sPowerSupply2 = null;
                string sOscilloScope = null;
                string sElectonicLoad = null;
                //string bPowerSupply1 = null;
                //string bPowerSupply2 = null;
                //string bOscilloScope = null;
                string bElectonicLoad = null;
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")) && (isTesterInit == false))
                {
                    isTesterInit = false;//init tester only once
                                         //step1 get tester data
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[2].Text+ "=" + node.Nodes[1].Nodes[2].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[3].Text + "=" + node.Nodes[1].Nodes[3].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[7].Text + "=" + node.Nodes[1].Nodes[7].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[0].Text != "PowerSupply1")
                        throw new Exception("PowerSupply1 Address set error");
                    else
                        sPowerSupply1 = node.Nodes[1].Nodes[0].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[1].Text != "PowerSupply2")
                        throw new Exception("PowerSupply2 Address set error");
                    else
                        sPowerSupply2 = node.Nodes[1].Nodes[1].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[2].Text != "OscilloScope")
                        throw new Exception("OscilloScope Address set error");
                    else
                        sOscilloScope = node.Nodes[1].Nodes[2].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[3].Text != "ElectonicLoad")
                        throw new Exception("ElectonicLoad Address set error");
                    else
                        sElectonicLoad = node.Nodes[1].Nodes[3].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[7].Text != "bElectonicLoad")
                        throw new Exception("ElectonicLoad Switch set error");
                    else
                        bElectonicLoad = node.Nodes[1].Nodes[7].Nodes[0].Text;
                    //step1 连线方式说明
                    AppendText("\n---------------------------------------------------------------------");
                    AppendText("\n Function Test 连线方式说明");
                    AppendText("\n PowerSupply1 VRECT 7V");
                    AppendText("\n PowerSupply2 VPP 3V");
                    AppendText("\n OscilloScope CH1:ANA_TEST// CH2:DIG_TEST// CH3:VOUT //CH4:VRECT");
                    AppendText("\n ElectonicLoad VOUT default off");
                    //step2 connect osc
                    bool bState = myCelfras.CFS_OSC_Init(sOscilloScope);
                    if (bState == false)
                        throw new Exception("CFS_OSC_Init()" + sOscilloScope);

                    //step3 connect powersupply2 VPP default is 3V
                    bState = myCelfras.CFS_PWR2_Init(sPowerSupply2);
                    if (bState == false)
                        throw new Exception("CFS_PWR_Init()" + sPowerSupply2);
                    myCelfras.CFS_PWR2_OnOff(false);
                    myCelfras.CFS_PWR2_SetVoltage(3.0);
                    myCelfras.CFS_PWR2_SetCurrent(2.0);
                    myCelfras.CFS_PWR2_OnOff(true);
                    //System.Threading.Thread.Sleep(1000);

                    //step4 connect powersupply1 VRECT 7V
                    bState = myCelfras.CFS_PWR_Init(sPowerSupply1);
                    if (bState == false)
                        throw new Exception("CFS_PWR_Init()" + sPowerSupply1);
                    myCelfras.CFS_PWR_OnOff(false);
                    myCelfras.CFS_PWR_SetVoltage(7.0);
                    myCelfras.CFS_PWR_SetCurrent(2.0);
                    myCelfras.CFS_PWR_OnOff(true);

                    //System.Threading.Thread.Sleep(1000);

                    //step5 connect load
                    bState = myCelfras.CFS_ELD_Init(sElectonicLoad);
                    if (bState == false)
                        throw new Exception("CFS_ELD_Init()" + sElectonicLoad);
                    myCelfras.CFS_ELD_OnOff(false);
                    myCelfras.CFS_ELD_SetCurrent(1.0);
                    myCelfras.CFS_ELD_SetModeCC();
                    return true;
                }
                return true;
            }

            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                return false;
            }
        }

        private bool run_Init_Tester_FT2(TreeNode node)
        {
            try
            {
                string sPowerSupply1 = null;
                string sPowerSupply2 = null;
                string sOscilloScope = null;
                string sElectonicLoad = null;
                //string bPowerSupply1 = null;
                //string bPowerSupply2 = null;
                //string bOscilloScope = null;
                string bElectonicLoad = null;
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")) && (isTesterInit == false))
                {
                    isTesterInit = false;//init tester only once
                                         //step1 get tester data
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[2].Text + "=" + node.Nodes[1].Nodes[2].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[3].Text + "=" + node.Nodes[1].Nodes[3].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[7].Text + "=" + node.Nodes[1].Nodes[7].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[0].Text != "PowerSupply1")
                        throw new Exception("PowerSupply1 Address set error");
                    else
                        sPowerSupply1 = node.Nodes[1].Nodes[0].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[1].Text != "PowerSupply2")
                        throw new Exception("PowerSupply2 Address set error");
                    else
                        sPowerSupply2 = node.Nodes[1].Nodes[1].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[2].Text != "OscilloScope")
                        throw new Exception("OscilloScope Address set error");
                    else
                        sOscilloScope = node.Nodes[1].Nodes[2].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[3].Text != "ElectonicLoad")
                        throw new Exception("ElectonicLoad Address set error");
                    else
                        sElectonicLoad = node.Nodes[1].Nodes[3].Nodes[0].Text;
                    if (node.Nodes[1].Nodes[7].Text != "bElectonicLoad")
                        throw new Exception("ElectonicLoad Switch set error");
                    else
                        bElectonicLoad = node.Nodes[1].Nodes[7].Nodes[0].Text;
                    //step1 连线方式说明
                    AppendText("\n ---------------------------------------------------------------------");
                    AppendText("\n Function Test 连线方式说明");
                    AppendText("\n PowerSupply1 VRECT 7V");
                    AppendText("\n PowerSupply2 ADC_EXT 0V");
                    AppendText("\n OscilloScope CH1:ANA_TEST// CH2:DIG_TEST// CH3:VOUT //CH4:VRECT");
                    AppendText("\n ElectonicLoad VOUT default off");
                    //step2 connect osc
                    bool bState = myCelfras.CFS_OSC_Init(sOscilloScope);
                    if (bState == false)
                        throw new Exception("CFS_OSC_Init()" + sOscilloScope);
                    //step3 connect powersupply2 ADC_EXT default is 0V
                    bState = myCelfras.CFS_PWR2_Init(sPowerSupply2);
                    if (bState == false)
                        throw new Exception("CFS_PWR_Init()" + sPowerSupply2);
                    myCelfras.CFS_PWR2_OnOff(false);
                    myCelfras.CFS_PWR2_SetVoltage(0.0);
                    myCelfras.CFS_PWR2_SetCurrent(2.0);
                    //myCelfras.CFS_PWR2_OnOff(true);
                    //System.Threading.Thread.Sleep(1000);

                    //step4 connect powersupply1 VRECT 7V
                    bState = myCelfras.CFS_PWR_Init(sPowerSupply1);
                    if (bState == false)
                        throw new Exception("CFS_PWR_Init()" + sPowerSupply1);
                    myCelfras.CFS_PWR_OnOff(false);
                    myCelfras.CFS_PWR_SetVoltage(7.0);
                    myCelfras.CFS_PWR_SetCurrent(2.0);
                    myCelfras.CFS_PWR_OnOff(true);

                    //System.Threading.Thread.Sleep(1000);

                    //step5 connect load
                    bState = myCelfras.CFS_ELD_Init(sElectonicLoad);
                    if (bState == false)
                        throw new Exception("CFS_ELD_Init()" + sElectonicLoad);
                    myCelfras.CFS_ELD_OnOff(false);
                    myCelfras.CFS_ELD_SetCurrent(1.0);
                    myCelfras.CFS_ELD_SetModeCC();
                    return true;
                }
                return true;
            }

            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                return false;
            }
        }
        #endregion

        #region calibration and otp write
        //step 1
        private Boolean Run_BGR_Voltage_Calibration(TreeNode node)
        {
            bool bState = false;
            if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")))
            {
                isCWQ1100CalTest = true;

                AppendText("\n" + node.Nodes[1].Nodes[0].Text + " = " + node.Nodes[1].Nodes[0].Nodes[0].Text);
                AppendText("\n" + node.Nodes[1].Nodes[1].Text + " = " + node.Nodes[1].Nodes[1].Nodes[0].Text);
                double dLimitH = 0.0;
                double dLimitL = 0.0;
                if (node.Nodes[1].Nodes[0].Text != "LimitL")
                    throw new Exception("LimitL set error");
                else
                    dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                if (node.Nodes[1].Nodes[1].Text != "LimitH")
                    throw new Exception("LimitH set error");
                else
                    dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);
                AppendText("\n CFS_TM_BGRVoltageCalibration");
                int iReg24 = 0;
                bState = myCelfras.CFS_TM_BGRVoltageCalibration(ref iReg24, dLimitL, dLimitH);
                if (bState == true)
                {
                    AppendText("\n iReg = " + iReg24);
                    dicOutput.Clear();
                    dicOutput.Add("Reg24",iReg24 + "");
                    UpdataDataGridView(dicOutput,node);
                    return true;
                }
                else
                {
                    AppendText("\n run_BGRVoltageCal,Cannot find value");
                    return false;
                }

            }
            return true;
        }

        //step 2
        private Boolean Run_OSC_Frequenty_Calibration(TreeNode node) {
            bool bState = false;
            if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")))
            {
                isCWQ1100CalTest = true;

                AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                double dLimitH = 0.0;
                double dLimitL = 0.0;
                if (node.Nodes[1].Nodes[0].Text != "LimitL")
                    throw new Exception("LimitL set error");
                else
                    dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                if (node.Nodes[1].Nodes[1].Text != "LimitH")
                    throw new Exception("LimitH set error");
                else
                    dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);
                AppendText("\n CFS_TM_BGRVoltageCalibration");
                int iReg24 = 0;
                bState = myCelfras.CFS_TM_BGRVoltageCalibration(ref iReg24, dLimitL, dLimitH);
                dicOutput.Clear();
                if (bState == true)
                {
                    AppendText("\n iReg = " + iReg24);
                    dicOutput.Add("Reg24", iReg24 + "");
                    dicOutput.Add("Result","PASS");
                    UpdataDataGridView(dicOutput,node);
                    return true;
                }
                else
                {
                    AppendText("\n run_BGRVoltageCal,Cannot find value");
                    dicOutput.Add("Result","FALSE");
                    UpdataDataGridView(dicOutput,node);
                    return false;
                }
            }
            return true;
        }

        //step 3
        private Boolean Run_VOUT_Calibration(TreeNode node) {
            if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")))
            {
                AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                double dLimitH = 0.0;
                double dLimitL = 0.0;
                if (node.Nodes[1].Nodes[0].Text != "LimitL")
                    throw new Exception("LimitL set error");
                else
                    dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                if (node.Nodes[1].Nodes[1].Text != "LimitH")
                    throw new Exception("LimitH set error");
                else
                    dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                AppendText("\n CFS_TM_VOUTVoltageCalibration");
                AppendText("\n 打开电子负载");

                myCelfras.CFS_ELD_SetCurrent(1.0);
                myCelfras.CFS_ELD_SetModeCC();
                myCelfras.CFS_ELD_OnOff(true);

                //需要接上电子负载,设置1A
                int iReg29 = 0;
                int iReg2A = 0;
                //myCelfras.CFS_OSC_Init("USB0::0x2A8D::0x1766::MY57251817::0::INSTR");
                //CFS_TM_VOUTVoltageCalibration
                //myCelfras.CFS_OSC_VoutCal_SendCmd();
                myCelfras.CFS_OSC_SendCmd(3);
                bool bState = myCelfras.CFS_TM_VOUTVoltageCalibration(3, ref iReg29, ref iReg2A, dLimitL, dLimitH);
                dicOutput.Clear();
                if (bState == true)
                {
                    AppendText("\n iReg29 = " + iReg29 + "iReg2A = " + iReg2A);

                    dicOutput.Add("Reg29", iReg29 + "");
                    dicOutput.Add("Reg2A", iReg2A + "");
                    dicOutput.Add("Result","PASS");
                    UpdataDataGridView(dicOutput,node);
                    //UpdataDataGridView("Reg29", iReg29+ "",node);
                    //UpdataDataGridView("Reg2A", iReg2A + "", node);
                    return true;
                }
                else
                {
                    dicOutput.Add("Result","FALSE");
                    UpdataDataGridView(dicOutput,node);
                    AppendText("\n run_VOUTVoltageCal,测试失败error");
                    return false;
                }

            }
            return true;
        }

        //step 4
        private Boolean Run_ADC_IOUT_Calibration(TreeNode node) {
            if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")))
            {
                AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                double dLimitH = 0.0;
                double dLimitL = 0.0;
                if (node.Nodes[1].Nodes[0].Text != "LimitL")
                    throw new Exception("LimitL set error");
                else
                    dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                if (node.Nodes[1].Nodes[1].Text != "LimitH")
                    throw new Exception("LimitH set error");
                else
                    dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);
                AppendText("\n 先调整电源为5.45V,使得示波器第4个通道测试值为5.4V");
                myCelfras.CFS_TM_ChangeVRECT(4);
                int iReg28 = 0;
                //myCelfras.CFS_OSC_Init("USB0::0x2A8D::0x1766::MY57251817::0::INSTR");
                //myCelfras.CFS_OSC_ADCIOUTCal_SendCmd();
                myCelfras.CFS_OSC_SendCmd(1);
                bool bState = myCelfras.CFS_TM_ADCIOUTCalibration(1, ref iReg28, dLimitL, dLimitH);
                dicOutput.Clear();
                if (bState == true)
                {
                    AppendText("\n iReg28 = " + iReg28);
                    
                    dicOutput.Add("Reg28",iReg28 + "");
                    dicOutput.Add("Result","PASS");
                    UpdataDataGridView(dicOutput,node);
                    return true;
                }
                else
                {
                    AppendText("\n run_ADCIOUTCal,测试失败error");

                    dicOutput.Add("Result","FALSE");
                    UpdataDataGridView(dicOutput,node);
                    return false;
                }
            }
            return true;
        }

        //step 5 otp write
        private Boolean Run_OTP_Write(TreeNode node) {
            int iRegC0 = 0;
            int iRegCC = 0;
            if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Replace(" ", "")))
            {
                AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                if (node.Nodes[1].Nodes[0].Text != "RegC0")
                    throw new Exception("RegC0 Address set error");
                else
                    iRegC0 = int.Parse(node.Nodes[1].Nodes[0].Nodes[0].Text);

                if (node.Nodes[1].Nodes[1].Text != "RegCC")
                    throw new Exception("RegCC Address set error");
                else
                    iRegCC = int.Parse(node.Nodes[1].Nodes[1].Nodes[0].Text);

                AppendText("\n 先调整VPP电源为8V,进行写OTP操作");
                bool bState = myCelfras.CFS_TM_OTPWrite(iRegC0, iRegCC);
                dicOutput.Clear();
                if (bState == true)
                {
                    AppendText("\n OTP Write OK");
                    dicOutput.Add("Result","PASS");
                    UpdataDataGridView(dicOutput,node);
                    //return true;
                }
                else
                {
                    AppendText("\n OTP Write fail");
                    dicOutput.Add("Result", "FALSE");
                    UpdataDataGridView(dicOutput,node);
                    return false;
                }

                bState = run_OTPCheck();
                if (bState == false)
                    throw new Exception("run_OTPCheck()");
                return true;
            }
            return true;
        }
        #endregion

        #region 
        //first close power and open power
        private bool run_OTPCheck()
        {
            try
            {
                bool bState = false;
                //close power supply
                //先关闭5.5V VRECT
                myCelfras.CFS_PWR_SetVoltage(5.5);
                myCelfras.CFS_PWR_SetCurrent(2.0);
                myCelfras.CFS_PWR_OnOff(false);
                System.Threading.Thread.Sleep(1000);
                //后关闭3V VPP
                myCelfras.CFS_PWR2_SetVoltage(3.0);
                myCelfras.CFS_PWR2_SetCurrent(2.0);
                myCelfras.CFS_PWR2_OnOff(false);
                System.Threading.Thread.Sleep(1000);

                //open power supply
                myCelfras.CFS_PWR2_SetVoltage(3.0);
                myCelfras.CFS_PWR2_SetCurrent(2.0);
                myCelfras.CFS_PWR2_OnOff(true);
                //
                myCelfras.CFS_PWR_SetVoltage(5.5);
                myCelfras.CFS_PWR_SetCurrent(2.0);
                myCelfras.CFS_PWR_OnOff(true);
                System.Threading.Thread.Sleep(1000);
                //bState = myCelfras.CFS_CWQ1100_I2CInit(0x24, 0.15);
                //if (bState == false)
                //   throw new Exception("CFS_CWQ1100_I2CInit()");

                bState = myCelfras.CFS_CWQ1100_OTP_Finish();
                if (bState)
                {
                    AppendText("\n otp check ok");
                    return true;
                }
                else
                    throw new Exception("CFS_CWQ1100_OTP_Finish()");
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                return false;
            }
        }
        #endregion 

        #region function test
        private Boolean Run_BGR_Voltage_Test(TreeNode node) {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    isCWQ1100FunctionTest = true;
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dVoltage = 0.0;
                    //function test vect=7.0 v
                    myCelfras.CFS_PWR_SetVoltage(7.0);
                    myCelfras.CFS_PWR_SetCurrent(2.0);
                    myCelfras.CFS_PWR_OnOff(true);
                    //begin BGR test
                    myCelfras.CFS_OSC_SendCmd(1);
                    bool bState = myCelfras.CFS_FT_BGRVoltageTest(1, ref dVoltage);

                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_FT_BGRVoltageTest()");
                }
                dicOutput.Clear();
                dicOutput.Add("Result","PASS");
                UpdataDataGridView(dicOutput,node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result","FALSE");
                UpdataDataGridView(dicOutput,node);
                return false;
            }
        }

        private Boolean Run_OSC_Frequency_Test(TreeNode node) {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    isCWQ1100FunctionTest = true;
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                    double dFrequency = 0.0;
                    myCelfras.CFS_OSC_SendCmd(2);
                    bool bState = myCelfras.CFS_FT_OSCFrequencyTest(2, ref dFrequency);

                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_FT_VDDVOUTALL()");
                }
                dicOutput.Clear();
                dicOutput.Add("Result", "PASS");
                UpdataDataGridView(dicOutput, node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool Run_LDOVoltageTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                    bool bState = myCelfras.CFS_FT_VDDVOUTALL(3);

                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    //Console.WriteLine(sFTLogs);
                    if (bState == false)
                        throw new Exception("CFS_FT_VDDVOUTALL()");
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result", "PASS");
                UpdataDataGridView(dicOutput, node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool run_ADCTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                    bool bState = myCelfras.CFS_FT_ADCTESTALL();
                    if (bState == false)
                        throw new Exception("CFS_FT_ADCTESTALL()");
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result","PASS");
                UpdataDataGridView(dicOutput,node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "False");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool run_CurrentSensorTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);
                    bool bState = myCelfras.CFS_FT_CurrentSenseTest1ALL(1);
                    if (bState == false)
                        throw new Exception("CFS_FT_CurrentSenseTest1ALL()");
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    //Console.WriteLine(sFTLogs);

                    bState = myCelfras.CFS_FT_CurrentSenseTest2ALL(1);
                    if (bState == false)
                        throw new Exception("CFS_FT_CurrentSenseTest2ALL()");
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result", "PASS");
                UpdataDataGridView(dicOutput, node);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool run_OCLTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);
                    double dVoltage1 = 0.0;
                    double dVoltage2 = 0.0;
                    bool bState = myCelfras.CFS_FT_OCLTEST(2, ref dVoltage1, ref dVoltage2);

                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_FT_OCLTEST()");
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result","PASS");
                UpdataDataGridView(dicOutput,node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool run_TestPortTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                    bool bState = myCelfras.CFS_FT_TESTPortTESTALL(1);

                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText( "\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_FT_TESTPortTEST()");
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result","PASS");
                UpdataDataGridView(dicOutput,node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }


        }

        private bool run_FunctionTest1(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                    isCWQ1100FunctionTest = true;
                    bool bState = false;
                    //Console.WriteLine("please change mode1 for function test");
                    //Console.WriteLine("power2-EXT-TS");
                    //Console.WriteLine("Press any Key to test..");
                    //MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    myCelfras.CFS_PWR2_SetVoltage(0);
                    MessageBox.Show("please change mode1 for function test power2-EXT-TS");
                    //myCelfras.CFS_PWR2_OnOff(false);
                    bState = myCelfras.CFS_CWQ1100_readCaldata();
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_CWQ1100_readCaldata");
                    //Console.ReadLine();
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result","PASS");
                UpdataDataGridView(dicOutput,node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }
        private bool run_FunctionTest2(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                    isCWQ1100FunctionTest = true;
                    MessageBox.Show("please change mode2 for function test VDD_5V-CH1 VDD_DIG-CH2 CLAMP-CH3 power2-ENB");
                    //Console.ReadLine();
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result", "PASS");
                UpdataDataGridView(dicOutput, node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool run_LDOVDDTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                    //<!-- 测试VDD_5V/CH1 -->
                    double dVoltage = 0.0;
                    bool bState = myCelfras.CFS_FT_LDOVDD5V(1, ref dVoltage);
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    //Console.WriteLine(sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_FT_LDOVDD5V()");
                    //< !--测试VDD_DIG / CH2-- >
                    bState = myCelfras.CFS_FT_LDOVDDDIG(2, ref dVoltage);
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    //Console.WriteLine(sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_FT_LDOVDDDIG()");
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result", "PASS");
                UpdataDataGridView(dicOutput, node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool run_ENBTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dVoltage = 0.0;
                    double dCurrent = 0.0;
                    bool bState = myCelfras.CFS_FT_ENBTest(1, ref dVoltage, ref dCurrent);
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    //Console.WriteLine(sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_FT_ENBTest()");
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result", "PASS");
                UpdataDataGridView(dicOutput, node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool run_OVPTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);


                    bool bState = myCelfras.CFS_FT_OVPTESTALL(3);
                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    AppendText("\n" + sFTLogs.ToString());
                    if (bState == false)
                        throw new Exception("CFS_FT_OVPTESTALL()");
                    //to do
                    //add code 判断pass/fall

                }
                dicOutput.Clear();
                dicOutput.Add("Result", "PASS");
                UpdataDataGridView(dicOutput, node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }

        private bool run_CloseTester(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    AppendText("\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text);
                    AppendText("\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text);

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                    //Console.WriteLine("------------Close Tester------------");
                    myCelfras.CFS_ELD_OnOff(false);
                    //先关闭5.5V VRECT
                    myCelfras.CFS_PWR_SetVoltage(5.5);
                    myCelfras.CFS_PWR_SetCurrent(2.0);
                    myCelfras.CFS_PWR_OnOff(false);
                    //System.Threading.Thread.Sleep(1000);
                    //后关闭3V VPP
                    myCelfras.CFS_PWR2_SetVoltage(3.0);
                    myCelfras.CFS_PWR2_SetCurrent(2.0);
                    bool bState = myCelfras.CFS_PWR2_OnOff(false);
                    if (bState == false)
                        throw new Exception("CFS_PWR2_OnOff()");
                    //to do
                    //add code 判断pass/fall
                }
                dicOutput.Clear();
                dicOutput.Add("Result", "PASS");
                UpdataDataGridView(dicOutput, node);
                return true;
            }
            catch (Exception ex)
            {
                AppendText("\n [ERR]" + ex.Message);
                dicOutput.Clear();
                dicOutput.Add("Result", "FALSE");
                UpdataDataGridView(dicOutput, node);
                return false;
            }
        }
        #endregion

        #endregion

        private bool run_DemoTest(TreeNode node)
        {
            try
            {
                if ("True".Equals(node.Nodes[0].Text.Split('=')[1].Trim()))
                {
                    richTextBox1.Text += "\n" + node.Nodes[1].Nodes[0].Text + "=" + node.Nodes[1].Nodes[0].Nodes[0].Text;
                    richTextBox1.Text += "\n" + node.Nodes[1].Nodes[1].Text + "=" + node.Nodes[1].Nodes[1].Nodes[0].Text;

                    double dLimitH = 0.0;
                    double dLimitL = 0.0;
                    if (node.Nodes[1].Nodes[0].Text != "LimitL")
                        throw new Exception("LimitL set error");
                    else
                        dLimitL = Convert.ToDouble(node.Nodes[1].Nodes[0].Nodes[0].Text);
                    if (node.Nodes[1].Nodes[1].Text != "LimitH")
                        throw new Exception("LimitH set error");
                    else
                        dLimitH = Convert.ToDouble(node.Nodes[1].Nodes[1].Nodes[0].Text);

                    bool bState = myCelfras.CFS_sample();

                    myCelfras.CFS_GetLastLog(ref sFTLogs);
                    richTextBox1.Text += "\n" + sFTLogs.ToString();
                    //Console.WriteLine(sFTLogs);
                    if (bState == false)
                        throw new Exception("CFS_sample()");
                    //to do
                    //add code 判断pass/fall
                }
                return true;
            }
            catch (Exception ex)
            {
                richTextBox1.Text += "\n [ERR]" + ex.Message;
                return false;
            }
        }

        
    }
}

 

工具类:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Civet
{
    class TreeViewUtils
    {
        public TreeView mTreeView;
        public string rootName = "";
        public RichTextBox richTextBox;
        public List<string> listPaths = new List<string>();

        public TreeViewUtils(TreeView treeView,RichTextBox textBox)
        {
            this.mTreeView = treeView;
            this.richTextBox = textBox;
        }

        public void InitTreeView()
        {
            this.mTreeView.CheckBoxes = true;
            this.mTreeView.DrawMode = System.Windows.Forms.TreeViewDrawMode.OwnerDrawAll;
            this.mTreeView.DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(mTreeView_DrawNode);
        }

        #region 部分节点的checkbox的隐藏
        private void mTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e)
        {
            if (e.Node.Level >= 2 && !"testNode".Equals(e.Node.Tag))
            {
                HideCheckBox(e.Node.TreeView, e.Node);
            }
            e.DrawDefault = true;
        }

        private const int TVIF_STATE = 0x8;
        private const int TVIS_STATEIMAGEMASK = 0xF000;
        private const int TV_FIRST = 0x1100;
        private const int TVM_SETITEM = TV_FIRST + 63;
        private void HideCheckBox(TreeView tvw, TreeNode node)
        {
            TVITEM tvi = new TVITEM();
            tvi.hItem = node.Handle;
            tvi.mask = TVIF_STATE;
            tvi.stateMask = TVIS_STATEIMAGEMASK;
            tvi.state = 0;
            SendMessage(tvw.Handle, TVM_SETITEM, IntPtr.Zero, ref tvi);
        }
        [StructLayout(LayoutKind.Sequential, Pack = 8, CharSet = CharSet.Auto)]
        private struct TVITEM
        {
            public int mask;
            public IntPtr hItem;
            public int state;
            public int stateMask;
            [MarshalAs(UnmanagedType.LPTStr)]
            public string lpszText;
            public int cchTextMax;
            public int iImage;
            public int iSelectedImage; public int cChildren; public IntPtr lParam;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, ref TVITEM lParam);
        #endregion

        #region 将xml文件转换为TreeNode
        public void Xml2Tree(string xmlFilePath)
        {
            //string xmlFilePath = "E:\test.xml";
            XmlDocument xmlDoc = GetXmlDocByFilePath(xmlFilePath);

            //xmlDoc.Load(this.xmlFilePath);
            //获取根节点的名字
            rootName = xmlDoc.DocumentElement.Name;
            //获取根节点
            XmlNode root = xmlDoc.SelectSingleNode(rootName);
            //把根节点添加到TreeView
            TreeNode rootTreeNode = new TreeNode();
            rootTreeNode.Tag = "hasChild";

            rootTreeNode.Text = rootName;
            mTreeView.Nodes.Add(rootTreeNode);

            TransXml(root.ChildNodes, rootTreeNode, "");
            listPaths.Add(xmlFilePath);
            //ShowNodeMes(listTreeNode); 
            
        }

        private void TransXml(XmlNodeList childNodes, TreeNode node, string order)
        {
            for (int i = 0; i < childNodes.Count; i++)
            {
                XmlNode xmlNode = childNodes[i];
                TreeNode subTreeNode = new TreeNode();

                //AddNode2List(xmlNode);

                #region 添加Attribute节点
                try
                {
                    if (xmlNode.Attributes.Count > 0 && xmlNode.Attributes != null)
                    {
                        AddAttr2Tree(xmlNode, subTreeNode);
                    }
                }
                catch (Exception ex)
                {
                }
                #endregion

                #region 添加非Attribute 节点
                if (xmlNode.HasChildNodes && xmlNode.ChildNodes[0].Name == "INPUT" && xmlNode.ChildNodes[1].Name == "OUTPUT")
                {
                    subTreeNode.Text = "[" + order + i.ToString() + "]" + xmlNode.Name;
                    subTreeNode.Name = xmlNode.Name;
                    subTreeNode.Tag = "testNode";
                    TransXml(xmlNode.ChildNodes, subTreeNode, "");
                }
                else if (xmlNode.HasChildNodes) {
                    subTreeNode.Text = xmlNode.Name;
                    subTreeNode.Name = xmlNode.Name;
                    subTreeNode.Tag = "hasChild";
                    TransXml(xmlNode.ChildNodes, subTreeNode, "");
                }
                else
                {
                    if (xmlNode.Value != null)
                    {
                        subTreeNode.Text = xmlNode.InnerText;
                        subTreeNode.Name = xmlNode.Name;
                        subTreeNode.Tag = "HaveValue";
                    }
                    /*
                    else
                    {
                        subTreeNode.Text = xmlNode.Name;
                        subTreeNode.Name = xmlNode.Name;
                        //subTreeNode.Tag = "NoValue";
                    }*/
                }
                node.Nodes.Add(subTreeNode);
                #endregion
            }
        }

        /// <summary>
        /// 将xml中node的Attribute值添加到TreeView中
        /// </summary>
        /// <param name="subXmlNode"></param>
        /// <param name="node"></param>
        private void AddAttr2Tree(XmlNode subXmlNode, TreeNode node)
        {
            TreeNode attrNode = new TreeNode();
            foreach (XmlAttribute attr in subXmlNode.Attributes)
            {
                attrNode.Name = attr.Name;
                attrNode.Text = attrNode.Name + " = " + attr.Value;
                attrNode.Tag = "isAttribute";
                node.Nodes.Add(attrNode);
            }
        }

        public XmlDocument GetXmlDocByFilePath(string xmlFilePath)
        {
            if (string.IsNullOrEmpty(xmlFilePath) || !File.Exists(xmlFilePath))
            {
                return null;
            }
            XmlDocument xmlDoc = new XmlDocument();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            try
            {
                XmlReader reader = XmlReader.Create(@xmlFilePath, settings);
                xmlDoc.Load(reader);
                reader.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("请检查Xml文件的格式是否正确,文件存放路径为:" + xmlFilePath + "\n错误信息提示:" + ex.ToString(), "提示");
            }
            return xmlDoc;
        }

        #endregion

        #region TreeView保存成xml文件处理
        #region 保存方式1
        public void SaveTreeView2Xml() {
            XmlWriter writer = null;
            XmlTextWriter textWriter = null;
            try
            {
                /*
                #region 使用XmlWriter类来进行xml文档的写入
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.IndentChars = "\t";
                settings.OmitXmlDeclaration = true;
                string xmlFilePath = @"E:\clone_project\CelfrasDevelopmentKit\Civet\Civet\bin\Debug\xmlWriter.xml";
                using (writer = XmlWriter.Create(xmlFilePath, settings))
                {
                    writer.WriteStartDocument(true);
                    Write2XML(mTreeView.Nodes, writer);
                    writer.WriteEndDocument();
                    writer.Flush();
                }
                #endregion
                */

                #region 使用XmlTextWriter类来进行xml文档的写入
                textWriter = new XmlTextWriter("XMLFile" + ".xml", Encoding.UTF8);
                textWriter.Indentation = 4;
                textWriter.Formatting = Formatting.Indented;
                textWriter.WriteStartDocument(true);
                Write2XML(mTreeView.Nodes, textWriter);
                textWriter.WriteEndDocument();
                textWriter.Flush();
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.ToString());
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    MessageBox.Show("保存成功!");
                }
            }
        }

        private void Write2XML(TreeNodeCollection coll, XmlWriter writer)
        {
            foreach (TreeNode node in coll)
            {
                richTextBox.AppendText(node.Text + "---" + node.Tag.ToString() + "\n");

                if (node.Tag.ToString() == "isAttribute")
                {
                    string[] str = node.Text.Split('=');
                    writer.WriteAttributeString(str[0].Trim(), str[1].Trim());
                }
                else if (node.Tag.ToString() == "testNode" || node.Tag.ToString() == "hasChild")
                {
                    if (node.Text.Contains("]"))
                    {
                        node.Text = node.Text.Split(']')[1];
                    }
                    writer.WriteStartElement(node.Text);
                    Write2XML(node.Nodes, writer);
                    writer.WriteEndElement();
                }
                else if (node.Tag.ToString() == "HaveValue")
                {
                    writer.WriteString(node.Text);
                }
            }
        }
        #endregion

        #region 保存方式2
        public void SaveTreeView2XML()
        {
            XDeclaration dec = new XDeclaration("1.0", "utf-8", "yes");
            XDocument doc = new XDocument(dec);
            XElement root = new XElement(rootName);

            foreach (TreeNode node in mTreeView.Nodes[0].Nodes)
            {
                XElement e = CreateElements(node, root);
                root.Add(e);
            }
            doc.Add(root);
            doc.Save("TreeView2XML.xml");
        }

        private XElement CreateElements(TreeNode node, XElement elementRoot)
        {
            XElement root = CreateElement(node);

            if (node.Nodes.Count > 0)
            {
                foreach (TreeNode n in node.Nodes)
                {
                    XElement e = CreateElements(n, root);
                    if (n.Tag != null)
                    {
                        if ("isAttribute".Equals(n.Tag.ToString()))
                        {
                            string[] str = n.Text.ToString().Replace(" ", "").Split('=');
                            root.SetAttributeValue(str[0], str[1]);
                        }
                        else if (n.Nodes.Count > 0)
                            root.Add(e);
                        else if (n.Tag.Equals("NoValue"))
                        {
                            root.Add(e);
                            //root.Add("<" + n.Name + ">" + "</" + n.Name + ">");
                        }
                        else
                            root.Add(n.Text.ToString());
                    }
                }
            }
            return root;
        }

        private XElement CreateElement(TreeNode node)
        {
            XElement element = null;

            Task<XElement> ts = Task.Factory.StartNew<XElement>((newNode) => {
                TreeNode n = (TreeNode)newNode;
                try
                {
                    if (n.Nodes.Count > 0)
                    {
                        element = new XElement(n.Name);
                    }
                }
                catch (Exception ex)
                {
                    richTextBox.AppendText(ex.Message);
                }
                return element;
            }, node);
            /*
            Task<XElement> task = new Task<XElement>((treeNode) => {
                TreeNode n = (TreeNode)treeNode;
                try
                {
                    if (n.Nodes.Count > 0)
                    {
                        element = new XElement(n.Name);
                    }
                }
                catch (Exception ex)
                {
                    richTextBox1.AppendText(ex.Message);
                }
                return element;
            },node);
            task.Start();*/
            return ts.Result;
        }
        #endregion
        #endregion

        #region TreeView关联DataGridView操作
        //将node信息添加到GridView
        public void AddNode2GridView(TreeNode node,DataTable dt)
        {
            TreeNodeCollection inputColl = node.Nodes[1].Nodes;
            TreeNodeCollection outputColl = node.Nodes[2].Nodes;

            if (inputColl.Count >= outputColl.Count) {
                for (int i = 0;i < inputColl.Count;i++) {
                    DataRow dr = dt.NewRow();
                    if (i >= outputColl.Count) {
                        dr["OutputName"] = "";
                        dr["OutputValue"] = "";
                    }
                    else{
                        dr["OutputName"] = node.Nodes[2].Nodes[i].Text;
                        dr["OutputValue"] = node.Nodes[2].Nodes[i].Nodes[0].Text;
                    }
                    dr["InputName"] = node.Nodes[1].Nodes[i].Text;
                    dr["InputValue"] = node.Nodes[1].Nodes[i].Nodes[0].Text;
                    dt.Rows.Add(dr);
                }
            }
            else{
                for (int i = 0; i < outputColl.Count; i++){
                    DataRow dr = dt.NewRow();
                    if (i >= inputColl.Count){
                        dr["InputName"] = "";
                        dr["InputValue"] = "";
                    }
                    else{
                        dr["InputName"] = node.Nodes[1].Nodes[i].Text;
                        dr["InputValue"] = node.Nodes[1].Nodes[i].Nodes[0].Text;
                    }
                    dr["OutputName"] = node.Nodes[2].Nodes[i].Text;
                    dr["OutputValue"] = node.Nodes[2].Nodes[i].Nodes[0].Text;
                    dt.Rows.Add(dr);
                }
            }
        }

        //循环遍历所有节点,找到对应DataGridView修改的节点
        public void CircleNode(string nodeName, string nodeText, TreeNodeCollection nodeColl)
        {
            foreach (TreeNode node in nodeColl)
            {
                if (nodeName.Equals(node.Text))
                {
                    node.Nodes[0].Text = nodeText;
                    return;
                }
                if (node.Nodes.Count > 0)
                {
                    CircleNode(nodeName, nodeText, node.Nodes);
                }
            }
        }
        #endregion

        #region 测试node保存到list
        public void AddNode2Dic(TreeNode node, Dictionary<int, TreeNode> dic)
        {
            if (node.Checked && "testNode".Equals(node.Tag))
            {
                byte b =  byte.Parse(node.Text.Substring(1, node.Text.IndexOf("]") - 1));
                int order = b;
                //int order = int.Parse(node.Text.Substring(1, node.Text.IndexOf("]") - 1));
                if (!dic.ContainsKey(order))
                {
                    dic.Add(order, node);
                }
                return;
            }
            else if (node.Checked && !"testNode".Equals(node.Tag))
            {
                if (node.Nodes.Count > 0 && node.Level < 2)
                {
                    foreach (TreeNode n in node.Nodes)
                    {
                        n.Checked = true;
                    }
                }
            }

            if (!node.Checked && "testNode".Equals(node.Tag))
            {
                int order = int.Parse(node.Text.Substring(1, node.Text.IndexOf("]") - 1));
                dic.Remove(order);
                return;
            }
            else if (!node.Checked && !"testNode".Equals(node.Tag))
            {
                if (node.Nodes.Count > 0 && node.Level < 2) {
                    foreach (TreeNode n in node.Nodes)
                    {
                        n.Checked = false;
                    }
                }
            }
        }
        #endregion 

    }
}

 

 

 

 

 

posted on 2017-09-29 09:00  写abcd的猴子  阅读(2980)  评论(2编辑  收藏  举报