Problem
Is there a straightforward way to parse XML files in C#? If that’s the case, what should you do?
Asked by domoaringatoo
Solution #1
It’s fairly straightforward. Although these are conventional approaches, you can design your own library to deal with it far more effectively.
Some instances are as follows:
XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object
xmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file
// Get elements
XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress");
XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge");
XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone");
// Display the results
Console.WriteLine("Address: " + girlAddress[0].InnerText);
Console.WriteLine("Age: " + girlAge[0].InnerText);
Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText);
There are also some other options to consider. Here’s an example: And I don’t believe there is a single best way to accomplish it; you must constantly choose what is most appropriate for you.
Answered by Lukas Ĺ alkauskas
Solution #2
If you’re using.NET 3.5 or higher, I’d recommend LINQ to XML.
Answered by Jon Galloway
Solution #3
Produce a collection of classes with xsd.exe using a good XSD Schema, and utilize an XmlSerializer to create an object tree from your XML and vice versa. If your model has few constraints, you could even use the Xml*Attributes to make a direct mapping between your model classes and the XML.
On MSDN, there is an introductory article on XML Serialization.
Constructing an XmlSerializer is a time-consuming process. If you want to parse/write numerous XML files, keep a reference to your XmlSerializer instance.
Answered by David Schmitt
Solution #4
You should use XmlReader to stream parse the XML if you’re processing a huge volume of data (several MB).
Anything else (XPathNavigator, XElement, XmlDocument, and even XmlSerializer if you store the entire created object graph) will consume a lot of memory and take a long time to load.
Of again, if you require all of the data to be stored in memory, you may not have much of a choice.
Answered by Simon Steele
Solution #5
Use XmlTextReader, XmlReader, XmlNodeReader and the System. Xml.XPath namespace. And (XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator).
XPath usually makes reading XML easier, which is probably what you’re looking for.
Answered by Vinko Vrsalovic
Post is based on https://stackoverflow.com/questions/55828/how-does-one-parse-xml-files