<Setup>
<group id="test1">
<group id="testist1">
<value>Exam1</value>
<value>Exam2</value>
</group2>
</group>
<group id="test2">
<group id="testist2">
<value>Exam1</value>
<value>Exam2</value>
</group>
</group>
</Setup>
I only want to get first childnode's attributes. -> test1, test2
so I tried this code but every attributes are printed.
xmlNode.ChildNodes[0].Attributes[0].Value
How can I get only first childnode? Thank you!
this is my full code.
private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList xNodeList;
if (xmlNode.HasChildNodes)
{
xNodeList = xmlNode.ChildNodes;
for (int x = 0; x <= xNodeList.Count - 1; x )
{
xNode = xmlNode.ChildNodes[x];
string nodetext = xNode.Name;
if (!nodetext.Contains("text"))
{
if (xNode.Attributes.Count > 0)
{
for (int i = 0; i < xNode.Attributes.Count; i )
{
lblExam.Text = xmlNode.ChildNodes[0].Attributes[0].Value;
}
}
}
treeNode.Nodes.Add(new TreeNode(nodetext));
tNode = treeNode.Nodes[x];
addTreeNode(xNode, tNode);
}
}
}
CodePudding user response:
One thing you might consider is using the System.Xml.Linq
namespace which is designed to search Xml hierarchies. In case you're not familiar, here are two examples of searches that let you pick exactly what you want out of the hierarchy. Now, I'm not 100% sure what your asking so if I miss the mark let me know in a comment and I'll try and adjust the examples, but no matter what you are looking for - a single attribute or whatever, you can find it using System.Xml.Linq
.
using System;
using System.Linq;
using System.Xml.Linq;
namespace xml_get_first_node
{
class Program
{
static void Main(string[] args)
{
XElement searchResult;
XElement xsource = XElement.Parse(source);
// EXAMPLE: Get the first group under Setup
Console.WriteLine("EXAMPLE: Get the first group under Setup");
searchResult = xsource.Elements("group").First();
Console.WriteLine(searchResult.ToString());
Console.WriteLine();
// EXAMPLE: Get the group with id="test2"
Console.WriteLine("EXAMPLE: Get the group with id='test2'");
searchResult =
xsource.Descendants()
.Where(xel=>(xel.Attribute("id") != null) && (xel.Attribute("id").Value == "test2")).First();
Console.WriteLine(searchResult.ToString());
}
const string source = @"
<Setup>
<group id=""test1"">
<group id=""testist1"">
<value>Exam1</value>
<value>Exam2</value>
</group>
</group>
<group id=""test2"">
<group id=""testist2"">
<value>Exam1</value>
<value>Exam2</value>
</group>
</group>
</Setup>";
}
}