Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read XML file into List<>?

Tags:

c#

xml

I have a List<> which I wrote into an XML file. Now I am trying to read the same file and write it back to List<>. Is there a method to do that?

like image 732
Nisha Avatar asked Mar 08 '12 14:03

Nisha


People also ask

How do I read XML files?

If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".

How do I view an XML file nicely?

How to open an XLM file. You can open XLM files with Microsoft Excel in Windows and macOS. However, Microsoft encourages you to migrate the XLM macro to a later version of Microsoft Visual Basic for Applications (VBA).

How do I read an XML String?

In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.

What is the best way to read XML in C #?

C# Program to Read and Parse an XML File Using XmlReader Class. The XmlReader class in C# provides an efficient way to access XML data. XmlReader. Read() method reads the first node of the XML file and then reads the whole file using a while loop.


2 Answers

I think the easiest way is to use the XmlSerializer:

XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));

using(FileStream stream = File.OpenWrite("filename"))
{
    List<MyClass> list = new List<MyClass>();
    serializer.Serialize(stream, list);
}

using(FileStream stream = File.OpenRead("filename"))
{
    List<MyClass> dezerializedList = (List<MyClass>)serializer.Deserialize(stream);
}
like image 195
Enyra Avatar answered Oct 15 '22 17:10

Enyra


You can try this (using System.Xml.Linq)

XDocument xmlDoc = XDocument.Load("yourXMLFile.xml");
var list = xmlDoc.Root.Elements("id")
                           .Select(element => element.Value)
                           .ToList();
like image 36
Dipesh Bhatt Avatar answered Oct 15 '22 18:10

Dipesh Bhatt