Reputation: 19
Trying to read each individual address value in each endpoint element and display each individual one in a seperate textbox.
<client>
<endpoint address="http://127.0.0.1:" />
<endpoint address="http://127.0.0.1:" />
<endpoint address="net.tcp://127.0.0.1:" />
</client>
I can read the XML data and display only the value of the last element. This is actually my first try at developing anything in C#.
Here is a bit of the code I have written:
XmlReader ReadFile = XmlReader.Create(AgentConfig.FileName);
while (ReadFile.Read())
{
if ((ReadFile.NodeType == XmlNodeType.Element) && (ReadFile.Name == "endpoint"))
{
if (ReadFile.HasAttributes)
{
textBox2.Text = ReadFile.GetAttribute("address");
textBox3.Text = ReadFile.GetAttribute("address");
}
}
}
In the meantime I will be looking for an answer on my own, but any input would definitely be appreciated! :)
Upvotes: 1
Views: 121
Reputation: 63065
you can add address Attributes to a List and finally set the text box like below
List<string> addresses = new List<string>();
XmlReader ReadFile = XmlReader.Create(AgentConfig.FileName);
while (ReadFile.Read())
{
if ((ReadFile.NodeType == XmlNodeType.Element) && (ReadFile.Name == "endpoint"))
{
if (ReadFile.HasAttributes)
{
addresses.Add(ReadFile.GetAttribute("address"));
}
}
}
if (addresses.Count >0)
{
textBox1.Text = addresses[0];
}
if (addresses.Count >= 1)
{
textBox2.Text = addresses[1];
}
Upvotes: 0
Reputation: 32681
I can read the XML data and display only the value of the last element.
You are facing this behaviour because you are overwriting your own values. If you want to append you need to change it like this
StringBuilder sb = new StringBuilder(); //before while loop
StringBuilder sb1 = new StringBuilder(); //before while loop
XmlReader ReadFile = XmlReader.Create(AgentConfig.FileName);
while (ReadFile.Read())
{
if ((ReadFile.NodeType == XmlNodeType.Element) && (ReadFile.Name == "endpoint"))
{
if (ReadFile.HasAttributes)
{
sb.Append(ReadFile.GetAttribute("address") + " ");
sb1.Append(ReadFile.GetAttribute("address") + " ");
}
}
}
//Then after your loop
textBox2.Text = sb.ToString();
textBox3.Text = sb1.ToString();
Upvotes: 0
Reputation: 75316
Using LINQ to XML is more convenient for your case:
var addresses = XDocument.Load(AgentConfig.FileName)
.Descendants("endpoint")
.Select(x => (string)x.Attribute("address"))
.ToList();
The result is the List<string>
, so, you can assign into your TextBoxes simply by index:
textBox1.Text = addresses[0];
textBox2.Text = addresses[1];
textBox3.Text = addresses[2];
Upvotes: 3