Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Read/Write XML File

Tags:

c#

xml

linq

It should be simple, but i'm having trouble reading in a simple xml file into a list of strings. Sample xml file is below:

<?xml version="1.0" encoding="utf-8" ?>
<directorylist>
    <dir>c:\TEST1\</dir>
    <dir>c:\TEST2\</dir>
</directorylist>

I want to read into a LIst. Can you recommend the best way to read/write.

Thnx

like image 889
Peter Avatar asked Aug 05 '26 08:08

Peter


2 Answers

using System.Xml.Linq;

var myList = from dir in myDocument.Descendants("dir")
             select dir;

That will give you a list of XElement objects. If you want strings, use select dir.Value;

like image 185
The Evil Greebo Avatar answered Aug 07 '26 01:08

The Evil Greebo


string xml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
                <directorylist>
                    <dir>c:\TEST1\</dir>
                    <dir>c:\TEST2\</dir>
                </directorylist>";

List<String> dirs = XElement.Parse(xml).Elements("dir")
                                       .Select(d => d.Value)
                                       .ToList();

you can use XElement.Load() to load xml directly from a file.

like image 26
Bala R Avatar answered Aug 07 '26 00:08

Bala R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!