Peter
Peter

Reputation: 1715

C# Read/Write XML File

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

Upvotes: 2

Views: 6237

Answers (4)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

To extract the strings, you can do:

List<string> dirs = XDocument.Load("yourfile.xml")
                             .Root.Elements("dir")
                             .Select(element => element.Value).ToList();

To write strings to a new XML file, you can do:

string[] dirs = new[] {
    "c:\\TEST1\\",
    "c:\\TEST2\\"
};
new XDocument(
    new XElement("directorylist",
        dirs.Select(dir => new XElement("dir", dir)))
).Save("yourfile.xml");

Upvotes: 2

Pete Stens&#248;nes
Pete Stens&#248;nes

Reputation: 5665

Try using LINQ to XML as it can do most of the heavy lifting for you (assuming you can target .NET 3 or better.

XElement root = XElement.Load("XMLFile1.xml");
IEnumerable<string> dirs = from el in root.Elements("dir")  //was directorylist
             select el.Value;

Upvotes: 1

Bala R
Bala R

Reputation: 108957

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.

Upvotes: 4

The Evil Greebo
The Evil Greebo

Reputation: 7138

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;

Upvotes: 6

Related Questions