user6334610
user6334610

Reputation:

C# XDocument Read all Nodes from XML-File

I have an XML-file like this:

<Inventory>
<Item>
<Name>Super Mario Bros</Name>
<Count>14</Count>
<Price>29,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1985</Year>
<ProductID>001</ProductID>
</Item>
<Item>
<Name>The Legend of Zelda</Name>
<Count>12</Count>
<Price>34,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1986</Year>
<ProductID>002</ProductID>
</Item>
<Item>
<Name>Street Fighter</Name>
<Count>82</Count>
<Price>19,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1987</Year>
<ProductID>003</ProductID>
</Item>
</Inventory>

(There are more Items, but they are all the same, except for the values.)

Now I want to iterate through each Item and extract every value from each node. Here's what I've tried so far:

        var xDocument = XDocument.Load(FilePath_CSVToXML);
        string xml = xDocument.ToString();
        StringBuilder sb = new StringBuilder();

        foreach (XElement xe in xDocument.Descendants("Inventory")) {
            sb.Append(xe);
        }

        Console.WriteLine(sb.ToString());
        Console.ReadLine();

The code above properly displays the XML-file, but it keeps the Nodes. (Name, Count, Price, etc.) I only want the values.

Upvotes: 1

Views: 2969

Answers (2)

jdweng
jdweng

Reputation: 34419

Try code below. The innertag of Comment doesn't need angle brackets so remove.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication49
{

    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            var results = doc.Descendants("Item").Select(x => new {
                name = (string)x.Element("Name"),
                count = (int)x.Element("Count"),
                price = (decimal)x.Element("Price"),
                comment = (string)x.Element("Comment"),
                artist = (string)x.Element("Artist"),
                publisher = (string)x.Element("Publisher"),
                genre = (string)x.Element("Genre"),
                year = (int)x.Element("Year"),
                productID = (string)x.Element("ProductID")
            }).ToList();

        }
    }


}

Upvotes: 1

Bali C
Bali C

Reputation: 31231

You need to use the Value property, i.e. sb.Append(xe.Value).

Upvotes: 1

Related Questions