简体   繁体   中英

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

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;

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.

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM