How does one parse XML files?


Question

Is there a simple method of parsing XML files in C#? If so, what?

1
492
6/21/2015 4:22:29 AM

Accepted Answer

I'd use LINQ to XML if you're in .NET 3.5 or higher.

238
2/23/2018 3:45:33 PM

It's very simple. I know these are standard methods, but you can create your own library to deal with that much better.

Here are some examples:

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

Also, there are some other methods to work with. For example, here. And I think there is no one best method to do this; you always need to choose it by yourself, what is most suitable for you.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon