2

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

Peter
  • 1,685
  • 3
  • 16
  • 22

4 Answers4

6
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;

The Evil Greebo
  • 7,013
  • 3
  • 28
  • 55
4
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.

Bala R
  • 107,317
  • 23
  • 199
  • 210
2

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");
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1

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;
Pete Stensønes
  • 5,595
  • 2
  • 39
  • 62