Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML to String List

Tags:

c#

xml

I have some code that I need to put into a string list in C# and I am reading this code from an XML files and the layout of it is something like below...

<?xml version="1.0"?>
<accountlist>
    <main>
        <account id="1" special_id="4923959">
            <username>Adam</username>
            <motto>Hello Everyone>
            <money>1004</money>
            <friends>394</friends>
            <rareid>9</rareid>
            <mission>10</mission>
        </account>
    </main>
</accountlist>

How can I put each account tag into a string list? from the first < account > to the < / account > tag?

Please do NOT tell me to go to the link below as it does NOT work!! How to read a XML file and write into List<>?

So far I have tried the below code, and the string list just stays empty

XDocument doc = XDocument.Parse(this._accountsFile);

            List<string> list = doc.Root.Elements("account")
                               .Select(element => element.Value)
                               .ToList();

            this._accounts = list;
like image 683
Liam Hardy Avatar asked Dec 24 '22 16:12

Liam Hardy


1 Answers

You'll have to use Descendants instead of Elements:

List<string> list = doc.Root.Descendants("account").Descendants()
                   .Select(element => element.Value)
                   .ToList();

Elements only returns child elements of the element (in case of the root element this means <main>).
Descendants returns the entire tree inside the element.

Also: You'll have to fix the tag <motto>Hello Everyone> to <motto>Hello Everyone</motto>

like image 80
Jon G Stødle Avatar answered Jan 02 '23 01:01

Jon G Stødle