Reputation: 1715
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
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
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
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
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