简体   繁体   中英

How to parse xml and loop through it from a string?

I want parse xml by looping through it. I referred this but I am not able to parse it using the Load function since it expects an URI parameter and not a string and so does LINQ to XML....Can anyone help me out ?

XmlDocument has a Load method which takes a filename, but also a LoadXml method which takes a string:

http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.loadxml.aspx

Similarly, XDocument has a Load method which takes a filename, or a Parse method which takes a string:

http://msdn.microsoft.com/en-us/library/bb345532.aspx

Similar to XDocument, we can use XElement which has Parse method to parse a xmlString.

See this code:

        string xmlString = @"<poi><city>stockholm</city><country>sweden</country><gpoint><lat>51.1</lat><lng>67.98</lng></gpoint></poi>";
        try
        {
            XElement x = XElement.Parse(xmlString);
            var latLng = x.Element("gpoint");

            Console.WriteLine(latLng.Element("lat").Value);
            Console.WriteLine(latLng.Element("lng").Value);
        }
        catch
        {
        }

Hope this helps.

string recentFileName = Path.Combine(folderPath, filexml);
XDocument xDoc = XDocument.Load(recentFileName);
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<root>" +
                    "<elem>some text<child/>more text</elem>" +
                    "</root>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM