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

[{'answer_id': 55829, 'author': 'Jon Galloway', 'author_id': 5, 'author_profile': 'https://Stackoverflow.com/users/5', 'pm_score': 9, 'selected': True, 'text': '<p>I\'d use <a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/linq-to-xml" rel="noreferrer">LINQ to XML</a> if you\'re in .NET 3.5 or higher.</p>\n'}, {'answer_id': 55831, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m not sure whether "best practice for parsing XML" exists. There are numerous technologies suited for different situations. Which way to use depends on the concrete scenario.</p>\n\n<p>You can go with <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_XML_.28formerly_called_XLINQ.29" rel="nofollow noreferrer">LINQ&nbsp;to&nbsp;XML</a>, <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx" rel="nofollow noreferrer"><code>XmlReader</code></a>, <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator.aspx" rel="nofollow noreferrer"><code>XPathNavigator</code></a> or even regular expressions. If you elaborate your needs, I can try to give some suggestions.</p>\n'}, {'answer_id': 55834, 'author': 'Vinko Vrsalovic', 'author_id': 5190, 'author_profile': 'https://Stackoverflow.com/users/5190', 'pm_score': 4, 'selected': False, 'text': '<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader(VS.80).aspx" rel="noreferrer"><code>XmlTextReader</code></a>, <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlreader(VS.80).aspx" rel="noreferrer"><code>XmlReader</code></a>, <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlnodereader(VS.80).aspx" rel="noreferrer"><code>XmlNodeReader</code></a> and the <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath(VS.80).aspx" rel="noreferrer"><code>System.Xml.XPath</code></a> namespace. And (<a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnavigator(VS.80).aspx" rel="noreferrer"><code>XPathNavigator</code></a>, <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathdocument(VS.80).aspx" rel="noreferrer"><code>XPathDocument</code></a>, <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathexpression(VS.80).aspx" rel="noreferrer"><code>XPathExpression</code></a>, <a href="http://msdn.microsoft.com/en-us/library/system.xml.xpath.xpathnodeiterator(VS.80).aspx" rel="noreferrer"><code>XPathnodeIterator</code></a>).</p>\n\n<p>Usually <a href="http://www.codeproject.com/KB/cpp/myXPath.aspx" rel="noreferrer"><code>XPath</code></a> makes reading XML easier, which is what you might be looking for.</p>\n'}, {'answer_id': 55836, 'author': 'Ash', 'author_id': 5023, 'author_profile': 'https://Stackoverflow.com/users/5023', 'pm_score': 3, 'selected': False, 'text': '<p>If you\'re using .NET 2.0, try <code>XmlReader</code> and its subclasses <code>XmlTextReader</code>, and <code>XmlValidatingReader</code>. They provide a fast, lightweight (memory usage, etc.), forward-only way to parse an XML file.</p>\n\n<p>If you need <a href="http://en.wikipedia.org/wiki/XPath" rel="noreferrer"><code>XPath</code></a> capabilities, try the <code>XPathNavigator</code>. If you need the entire document in memory try <code>XmlDocument</code>.</p>\n'}, {'answer_id': 55840, 'author': 'Lukas Šalkauskas', 'author_id': 5369, 'author_profile': 'https://Stackoverflow.com/users/5369', 'pm_score': 8, 'selected': False, 'text': '<p>It\'s very simple. I know these are standard methods, but you can create your own library to deal with that much better.</p>\n\n<p>Here are some examples:</p>\n\n<pre><code>XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object\nxmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file\n\n// Get elements\nXmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress");\nXmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge"); \nXmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone");\n\n// Display the results\nConsole.WriteLine("Address: " + girlAddress[0].InnerText);\nConsole.WriteLine("Age: " + girlAge[0].InnerText);\nConsole.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText);\n</code></pre>\n\n<p>Also, there are some <a href="http://www.google.lt/search?hl=lt&amp;client=firefox-a&amp;rls=org.mozilla%3Aen-US%3Aofficial&amp;hs=pLz&amp;q=parse+XML+C%23&amp;btnG=Paie%C5%A1ka&amp;meta=" rel="noreferrer">other methods</a> to work with. For example, <a href="http://support.microsoft.com/kb/307548" rel="noreferrer">here</a>. 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.</p>\n'}, {'answer_id': 55891, 'author': 'David Schmitt', 'author_id': 4918, 'author_profile': 'https://Stackoverflow.com/users/4918', 'pm_score': 6, 'selected': False, 'text': '<p>Use a good <a href="http://en.wikipedia.org/wiki/XSD" rel="noreferrer">XSD Schema</a> to create a set of classes with <a href="http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx" rel="noreferrer">xsd.exe</a> and use an <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx" rel="noreferrer"><code>XmlSerializer</code></a> to create a object tree out of your XML and vice versa. If you have few restrictions on your model, you could even try to create a direct mapping between you model classes and the XML with the Xml*Attributes.</p>\n\n<p>There is <a href="http://msdn.microsoft.com/en-us/library/182eeyhh.aspx" rel="noreferrer">an introductory article about XML Serialisation</a> on MSDN.</p>\n\n<p>Performance tip: Constructing an <code>XmlSerializer</code> is expensive. Keep a reference to your <code>XmlSerializer</code> instance if you intend to parse/write multiple XML files. </p>\n'}, {'answer_id': 55965, 'author': 'Simon Steele', 'author_id': 4591, 'author_profile': 'https://Stackoverflow.com/users/4591', 'pm_score': 5, 'selected': False, 'text': '<p>If you\'re processing a large amount of data (many megabytes) then you want to be using <code>XmlReader</code> to stream parse the XML.</p>\n\n<p>Anything else (<code>XPathNavigator</code>, <code>XElement</code>, <code>XmlDocument</code> and even <code>XmlSerializer</code> if you keep the full generated object graph) will result in <a href="https://stackoverflow.com/questions/1505075/deciding-on-when-to-use-xmldocument-vs-xmlreader">high memory usage</a> and also a very slow load time.</p>\n\n<p>Of course, if you need all the data in memory anyway, then you may not have much choice.</p>\n'}, {'answer_id': 42276676, 'author': 'Wojtpl2', 'author_id': 4809321, 'author_profile': 'https://Stackoverflow.com/users/4809321', 'pm_score': 1, 'selected': False, 'text': '<p>You can use <a href="https://github.com/wojtpl2/ExtendedXmlSerializer" rel="nofollow noreferrer">ExtendedXmlSerializer</a> to serialize and deserialize.</p>\n\n<p><strong>Instalation</strong>\nYou can install ExtendedXmlSerializer from <a href="https://www.nuget.org/packages/ExtendedXmlSerializer/" rel="nofollow noreferrer">nuget</a> or run the following command:</p>\n\n<pre><code>Install-Package ExtendedXmlSerializer\n</code></pre>\n\n<p><strong>Serialization:</strong></p>\n\n<pre><code>ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();\nvar obj = new Message();\nvar xml = serializer.Serialize(obj);\n</code></pre>\n\n<p><strong>Deserialization</strong></p>\n\n<pre><code>var obj2 = serializer.Deserialize&lt;Message&gt;(xml);\n</code></pre>\n\n<p><strong>Standard XML Serializer in .NET is very limited.</strong></p>\n\n<ul>\n<li>Does not support serialization of class with circular reference or class with interface property,</li>\n<li>Does not support Dictionaries,</li>\n<li>There is no mechanism for reading the old version of XML,</li>\n<li>If you want create custom serializer, your class must inherit from IXmlSerializable. This means that your class will not be a POCO class,</li>\n<li>Does not support IoC.</li>\n</ul>\n\n<p><strong>ExtendedXmlSerializer can do this and much more.</strong></p>\n\n<p>ExtendedXmlSerializer support <strong>.NET 4.5</strong> or higher and <strong>.NET Core</strong>. You can integrate it with WebApi and AspCore. </p>\n'}, {'answer_id': 45176663, 'author': 'Tapan kumar', 'author_id': 1784941, 'author_profile': 'https://Stackoverflow.com/users/1784941', 'pm_score': 2, 'selected': False, 'text': '<p>You can parse the XML using this library <code>System.Xml.Linq</code>. Below is the sample code I used to parse a XML file </p>\n\n<pre><code>public CatSubCatList GenerateCategoryListFromProductFeedXML()\n{\n    string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);\n\n    XDocument xDoc = XDocument.Load(path);\n\n    XElement xElement = XElement.Parse(xDoc.ToString());\n\n\n    List&lt;Category&gt; lstCategory = xElement.Elements("Product").Select(d =&gt; new Category\n    {\n        Code = Convert.ToString(d.Element("CategoryCode").Value),\n        CategoryPath = d.Element("CategoryPath").Value,\n        Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category\n        SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category\n    }).GroupBy(x =&gt; new { x.Code, x.SubCategoryName }).Select(x =&gt; x.First()).ToList();\n\n    CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);\n\n    return catSubCatList;\n}\n</code></pre>\n'}, {'answer_id': 46790003, 'author': 'Joel Harkes', 'author_id': 1275832, 'author_profile': 'https://Stackoverflow.com/users/1275832', 'pm_score': 3, 'selected': False, 'text': '<p>In Addition you can use XPath selector in the following way (easy way to select specific nodes):</p>\n\n<pre><code>XmlDocument doc = new XmlDocument();\ndoc.Load("test.xml");\n\nvar found = doc.DocumentElement.SelectNodes("//book[@title=\'Barry Poter\']"); // select all Book elements in whole dom, with attribute title with value \'Barry Poter\'\n\n// Retrieve your data here or change XML here:\nforeach (XmlNode book in nodeList)\n{\n  book.InnerText="The story began as it was...";\n}\n\nConsole.WriteLine("Display XML:");\ndoc.Save(Console.Out);\n</code></pre>\n\n<p><a href="https://msdn.microsoft.com/en-us/library/hcebdtae(v=vs.110).aspx" rel="noreferrer">the documentation</a></p>\n'}, {'answer_id': 47329657, 'author': 'shaishav shukla', 'author_id': 5343801, 'author_profile': 'https://Stackoverflow.com/users/5343801', 'pm_score': 1, 'selected': False, 'text': '<p>You can use XmlDocument and for manipulating or retrieve data from attributes you can Linq to XML classes.</p>\n'}, {'answer_id': 48951398, 'author': 'PJRobot', 'author_id': 2742811, 'author_profile': 'https://Stackoverflow.com/users/2742811', 'pm_score': 4, 'selected': False, 'text': '<p>I have just recently been required to work on an application which involved the parsing of an XML document and I agree with Jon Galloway that the LINQ to XML based approach is, in my opinion, the best. I did however have to dig a little to find usable examples, so without further ado, here are a few!</p>\n\n<p>Any comments welcome as this code works but may not be perfect and I would like to learn more about parsing XML for this project!</p>\n\n<pre><code>public void ParseXML(string filePath)  \n{  \n    // create document instance using XML file path\n    XDocument doc = XDocument.Load(filePath);\n\n    // get the namespace to that within of the XML (xmlns="...")\n    XElement root = doc.Root;\n    XNamespace ns = root.GetDefaultNamespace();\n\n    // obtain a list of elements with specific tag\n    IEnumerable&lt;XElement&gt; elements = from c in doc.Descendants(ns + "exampleTagName") select c;\n\n    // obtain a single element with specific tag (first instance), useful if only expecting one instance of the tag in the target doc\n    XElement element = (from c in doc.Descendants(ns + "exampleTagName" select c).First();\n\n    // obtain an element from within an element, same as from doc\n    XElement embeddedElement = (from c in element.Descendants(ns + "exampleEmbeddedTagName" select c).First();\n\n    // obtain an attribute from an element\n    XAttribute attribute = element.Attribute("exampleAttributeName");\n}\n</code></pre>\n\n<p>With these functions I was able to parse any element and any attribute from an XML file no problem at all!</p>\n'}]
['https://Stackoverflow.com/questions/55828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4361/']