0
<?xml version="1.0" standalone="yes"?>
<Subject>
  <Book>
    <Name>ASP.NET</Name>
    <Author>ABC</Author>
    <Published>2018</Published>
    <Price>$100</Price>
  </Book>
</Subject>   

Above is the xml file i have. I want to store xml nodes and values using Dictionary or Collections in C# and display those on message box using winforms.

Output should be as:

Name: ASP.NET   
Author: ABC   
Published: 2018   
Price: $100     

I have tried the following but getting lots of errors...

var doc = XDocument.Load(@"xmlfile.xml");
var rootNodes = doc.Root.DescendantNodes().OfType<XElement>();
var keyValuePairs = from n in rootNodes
                    select new
                    {
                        TagName = n.Name,
                        TagValue = n.Value
                    };

var allitems = new Dictionary<string, string>();
foreach (var node in rootNodes)
{
    allitems.Add(node.Name.ToString(), node.Value);
    //string str = string.Join("",allitems);
    MessageBox.Show(allitems);
}
Rand Random
  • 7,300
  • 10
  • 40
  • 88
Virat ABD
  • 19
  • 7

2 Answers2

0

You should first parse the XML into objects (Convert XML String to Object).

Then you can simply implement the ToString() method of that type, to print it up nicely.

Coder14
  • 1,305
  • 1
  • 9
  • 26
  • Can u please Explain it briefly.. @Coder14 – Virat ABD May 31 '18 at 05:07
  • I'm not sure what I need to explain more. Read the answers of the question I linked to know how to convert XML to objects. Once you have the objects, you can implement the ToString() method, or manually access the properties you want to print. For example: var output = @$"Name: {book.Name} Author: {book.Author} Published: {book.Published} Price: ${book.Price}"; BTW this sounds a lot like a school assignment. We're not going to make your homework. Maybe check your (or someone else's) notes how you learned to parse XML. – Coder14 May 31 '18 at 09:00
0

I think for this part, you need to convert it into .cs file and XML cannot retrieve the messagebox...

Inside of the .cs file, you also can try to put the code for messagebox

MessageBox.Show( // put something over there and you want to show this output );