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

2
  • 3
    You should post the code you are having trouble with. Commented Jun 27, 2011 at 15:55
  • This discussion on stack overflow should be a good starting point on xml reading: stackoverflow.com/questions/55828/… Commented Jun 27, 2011 at 15:56

4 Answers 4

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;

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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");

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.