将所有节点属性保存为XML

本文关键字:保存 XML 属性 节点 | 更新日期: 2023-09-27 18:24:02

我编写了一段代码,读取一个XMl文件,然后使用节点名称构建XML文件的树视图。我想知道如何使用属性而不是组件(节点)名称?

例如,在以下XML文件中,而不是在action(s)中,除了前两个父节点(Reporttest)之外,我希望在树视图中打印copypaste等。

XML文件:

<Report version="2.1" xmlns="http://www.froglogic.com/XML2">
<test name="Example">
    <action name="delet">
        this is delet
    </action>
    <action name="copy">
        this is copy
    </action>
    <action name="paste">
        this is paste
    </action>
    <action name="manipulate">
        this is manipulate
    </action>
    <action name="copy">
        this is copy
    </action>
    <action name="paste">
        this is paste
    </action>
    <action name="manipulate">
        this is manipulate
    </action>
    <action name="change">
        this is change
    </action>
</test>
</Report>

C#代码:

private void File2_load(object sender, EventArgs e)
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(File2Path.Text);
            treeView2.Nodes.Clear();
            treeView2.Nodes.Add(new TreeNode(doc.DocumentElement.Name));
            TreeNode tNode = new TreeNode();
            tNode = treeView2.Nodes[0];
            AddNode(doc.DocumentElement, tNode);
            treeView2.ExpandAll();
            treeView2.CheckBoxes = true;
        }
        catch (XmlException xmlEx)
        {
            MessageBox.Show(xmlEx.Message);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

更新

private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
    {
        XmlNode xNode;
        TreeNode tNode;
        XmlNodeList nodeList;
        int i;
        if (inXmlNode.HasChildNodes)
        {
            nodeList = inXmlNode.ChildNodes;
            for (i = 0; i <= nodeList.Count - 1; i++)
            {
                xNode = inXmlNode.ChildNodes[i];
                inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
                tNode = inTreeNode.Nodes[i];
                AddNode(xNode, tNode);
            }
        }
        else
        {
            inTreeNode.Text = (inXmlNode.OuterXml).Trim();
        }
    }

将所有节点属性保存为XML

更改

            xNode = inXmlNode.ChildNodes[i];
            inTreeNode.Nodes.Add(new TreeNode(xNode.Name));

            xNode = inXmlNode.ChildNodes[i];
            TreeNode childTreeNode;
            if (xNode.LocalName == "action" && xNode.NodeType == XmlNodeType.Element)
            {
              childTreeNode = new TreeNode(xNode.Attributes["name"].Value);
            }
            else
            {
              childTreeNode = new TreeNode(xNode.Name);
            }
            inTreeNode.Nodes.Add(childTreeNode);

根据XML输入的复杂性以及XML输入中可能包含的节点,您可能需要对NodeTypeLocalName添加进一步的检查。