Click here to Skip to main content
15,888,802 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Based on the code from the link "http://www.codeproject.com/Tips/146237/Reading-XML-documents-using-LINQ". If I need to retrieve the data of <Subject1> and <Subject2>, how should the new c# be by replacing this code "listBox1.Items.Add(b.Element("Subject").Value.Trim());"

Thanks!


C#
var books = from nodes in System.Xml.Linq.XElement.Load("Books.xml").Elements("Book") select nodes;
 
            if (books != null)
            {
                foreach (var b in books)
                {
                    listBox1.Items.Add(b.Element("Subject").Value.Trim());
 
                }
            }


XML
<Books>
  <Book>
    <Subject>
    <Subject1>Subject1a</Subject1>
    <Subject2>Subject1a</Subject2>
    </Subject>
    <Content>
      History,Geography
    </Content>
  </Book>
 
  <Book>
    <Subject>
    <Subject1>Subject2b</Subject1>
    <Subject2>Subject2b</Subject2>
    </Subject>
    <Content>
      Biology,Chemistry,Physics
    </Content>
  </Book>
</Books>
Posted
Comments
Sergey Alexandrovich Kryukov 7-Jun-15 11:09am    
Wrong approach. You should right code understanding what you are doing, not play with existing fragment of code.
Programming is not replacing one fragment of code with another, it is thinking.
—SA

1 solution

It should be something like this:

C#
XDocument xdoc = XDocument.Load("fullfilepath.xml");

var qry  = xdoc.Root
		.Descendants("Subject")
		.Select(n=> new 
			{
				sub1 = n.Element("Subject1").Value,
				sub2 = n.Element("Subject2").Value
			}).ToList();

ListBox1.DataSource = qry;

Result:
sub1      sub2
Subject1a Subject1a 
Subject2b Subject2b


For further information, please see:
XDocument.Load Method (String)[^]
How to: Bind a Windows Forms ComboBox or ListBox Control to Data[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900