C# 将所有节点属性保存到XML
我编写了一段代码,读取C# 将所有节点属性保存到XML,c#,xml,treenode,C#,Xml,Treenode,我编写了一段代码,读取XMl文件,然后使用节点名称构建XMl文件的树视图。我想知道如何使用属性而不是组件(节点)名称 例如,在以下XML文件中,而不是action(s),我想在树状视图中打印copy或paste,除前两个父节点(Report和test)之外 XML文件: <Report version="2.1" xmlns="http://www.froglogic.com/XML2"> <test name="Example"> <action name
XMl
文件,然后使用节点名称构建XMl
文件的树视图。我想知道如何使用属性而不是组件(节点)名称
例如,在以下XML
文件中,而不是action
(s),我想在树状视图中打印copy
或paste
,除前两个父节点(Report
和test
)之外
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>
更新
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();
}
}
private void AddNode(XmlNode中的XmlNode,TreeNode中的TreeNode)
{
xmlnodexnode;
三烯醇化物;
XmlNodeList节点列表;
int i;
if(inXmlNode.HasChildNodes)
{
nodeList=inXmlNode.ChildNodes;
对于(i=0;i变化
到
根据XML输入的复杂性和XML输入中可能包含的节点,您可能需要在NodeType
和LocalName
上添加进一步的检查。可能的重复项,但我需要的是前两个部分的名称,其余部分显示在树状视图属性中。显示您调用的方法AddNode
的代码,我们可以帮助更改它。@MartinHonnen请查看更新。您不能有两个同名的属性。我已将Getattributes(“name”)
更改为attributes[“name”].Value
。因为发生了错误。@Saber,是的,对此很抱歉,GetAttribute
是XmlElement
上的一个方法,因此我需要首先对元素进行强制转换。我已编辑了示例,如果您的问题现在已解决,则您可以接受答案。
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();
}
}
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);