simple xml parsing simple xml parsing xml xml

simple xml parsing


Using Linq for XML:

   XDocument doc= XDocument.Parse("<poi><city>stockholm</city><country>sweden</country><gpoint><lat>51.1</lat><lng>67.98</lng></gpoint></poi>");    var points=doc.Descendants("gpoint");    foreach (XElement current in points)    {        Console.WriteLine(current.Element("lat").Value);        Console.WriteLine(current.Element("lng").Value);    }    Console.ReadKey(); 


using System.IO;using System.Xml;using System.Xml.XPath;

. . .

    string xml = @"<poi>                           <city>stockholm</city>                       <country>sweden</countr>                        <gpoint>                                    <lat>51.1</lat>                                    <lng>67.98</lng>                            </gpoint>                   </poi>";    XmlReaderSettings set = new XmlReaderSettings();    set.ConformanceLevel = ConformanceLevel.Fragment;    XPathDocument doc =         new XPathDocument(XmlReader.Create(new StringReader(xml), set));    XPathNavigator nav = doc.CreateNavigator();    Console.WriteLine(nav.SelectSingleNode("/poi/gpoint/lat"));    Console.WriteLine(nav.SelectSingleNode("/poi/gpoint/lng"));

You could of course use xpath SelectSingleNode to select the <gpoint> element into a variable.


Even simpler than Mitch Wheat's answer, since the fragment in question is a well-formed XML document:

using System.Xml;using System.IO;...string xml = @"<poi>                  <city>stockholm</city>                  <country>sweden</country>                  <gpoint>                    <lat>51.1</lat>                    <lng>67.98</lng>                  </gpoint>              </poi>";XmlDocument d = new XmlDocument();d.Load(new StringReader(xml));Console.WriteLine(d.SelectSingleNode("/poi/gpoint/lat").InnerText);Console.WriteLine(d.SelectSingleNode("/poi/gpoint/lng").InnerText);