Reputation: 1069
I have a xml file like this
< insrtuction name=inst1>
< destnation >
< connection> con1 < /connection> < /destination>< destnation >
< connection> con2 < /connection> < /destination>< /instruction>
< insrtuction name=inst2>
< destnation >
< connection> con3 < /connection> < /destination>< destnation >
< connection> con4 < /connection> < /destination>< /instruction>
I have to get all the connections. code I wrote
private void button5_Click(object sender, EventArgs e)
{
xml = new XmlDocument();
xml.Load("D:\\connections.xml");
string text = "";
XmlNodeList xnList = xml.SelectNodes("/instruction/destination");
foreach (XmlNode xn in xnList)
{
string configuration = xn["connection"].InnerText;
text = text + configuration + "\r\n" + "\r\n";
}
textBox1.Text=text;
}
Output I am getting is
con1
con2
con3
con4
According to my new requirement output should be
Instruction Name : inst1
connection: con1
connection: con1
Instruction Name : inst2
connection: con3
connection: con4
I am new to .net, I am using 2.0 frame work, I cant use LINQ. Thanks
Upvotes: 0
Views: 2390
Reputation: 37710
You may write this :
private void button5_Click(object sender, EventArgs e)
{
xml = new XmlDocument();
xml.Load("D:\\connections.xml");
StringBuilder sb = new StringBuilder();
XmlNodeList xnList = xml.SelectNodes("/instruction");
foreach (XmlNode xn in xnList)
{
sb.AppendLine(xn.Attribute["name"].Value);
foreach(XmlNode subNodes in xn.SelectNodes("destination/connection") {
sb.AppendLine(subNodes.InnerText);
}
}
textBox1.Text=sb.ToString();
}
However, I think this a very easy case you could have solved yourself. There is no technical challenge here. I advise you to take a training, read a book and dive into the documentation.
PS: not the use of StringBuilder
instead of string concatenation...
Upvotes: 1
Reputation: 139187
Something like this, with an inner loop:
XmlNodeList xnList = xml.SelectNodes("/instruction");
foreach (XmlElement xn in xnList)
{
text += "Instruction Name : " + xn.GetAttribute("name") + Environment.NewLine + Environment.NewLine;
foreach (XmlElement cn in xn.SelectNodes("connection"))
{
text += "Connection : " + xn.InnerText + Environment.NewLine + Environment.NewLine;
}
}
Upvotes: 1
Reputation: 1081
try like this:
xml = new XmlDocument();
xml.Load("D:\\connections.xml");
string val="";
string text = "";
foreach (XmlNode child in xml.DocumentElement.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element)
{
//MessageBox.Show(child.Name + ": " + child.InnerText.ToString());
node = child.Name; //here you will get node name
if (node.Equals("Instruction"))
{
val = child.InnerText.ToString(); //value of the node
//MessageBox.Show(node + ": " + val);
}
}
}
Upvotes: 2