<Input>
<City>Ludhiana</City>
<State>Punjab</State>
<Country>India</Country>
<Phone>01613535366</Phone>
</Input>
Now you want to parse the contents of these XML elements and retrieve them into various string objects. Next code is exactly to serve this purpose
//include these namespaces
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.IO;
//real code to read strings
string xml = "..xml above as a string..";
TextReader tr = new StringReader(xml);
XDocument xmlDoc = XDocument.Load(tr);
XElement inputXmlElement = xmlDoc.Element("Input");
string city = (string) inputXmlElement.Element("City");
string state = (string) inputXmlElement.Element("State");
string country = (string) inputXmlElement.Element("Country");
string phone = (string) inputXmlElement.Element("Phone");
You can notice, how dramatically the lines of Code has decreased.
Note: For using LINQ in VS 2005 you have some prerequisites i.e. you need to install LINQ extensions first.
1 comment:
This helped me. Thanks!
Alternatively, you could:
string xml = "..xml above as a string..";
XDocument xmlDoc = XDocument.Parse(xml);
Post a Comment