How do I read and parse an XML file in C#?
http://www.google.com/search?hl=en&q=c%23+xml+parsing
Are new users even to lazy to even google? sigh
There are lots of way, some:
- XmlSerializer. use a class with the target schema you want to read - use XmlSerializer to get the data in an Xml loaded into an instance of the class.
- Linq 2 xml
- XmlTextReader.
- XmlDocument
- XPathDocument (read-only access)
You can either:
- Use XmlSerializer class
- Use XmlDocument class
Examples are on the msdn pages provided
XmlDocument to read an XML from string or from file.
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
then find a node below it ie like this
XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");
XmlNode[] nodes = doc.DocumentElement.SelectNodes("/book/title");
or
foreach(XmlNode node in doc.DocumentElement.ChildNodes){
string text = node.InnerText; //or loop through its children as well
}
then read the text inside that node like this
string text = node.InnerText;
or read an attribute
string attr = node.Attributes["theattributename"].InnerText
Also, VB.NET has much better xml parsing support via the compiler than C#. If you have the option and the desire, check it out.
Whats with all the posts about searching google? I just don't get it, isn't this the point of Stack Overflow? People ask questions, other people answer em.
Yah, you could search google, and get a ton of hits. Some bloggers might have written a post 3 years ago. Other bloggers might not have a clue of what they are talking about.
The reason why you post here and let people answer and vote, is so the best practices/implementations float to the top. You don't have to go searching through old blog posts, sifting through whats right and wrong. Heck, you dont even know what's right vs. wrong, here the experts help you out with that.
This is what user created content is all about.
The most convinient and simple way is to use LINQ to XML (new featue of C#). Example:
// Loading from a file, you can also load from a stream
var doc = XDocument.Load(@"C:\contacts.xml");
// Query the data and write out a subset of contacts
var q = from c in doc.Descendants("contact")
where (int)c.Attribute("contactId") < 4
select (string)c.Element("firstName") + " " +
(string)c.Element("lastName");
foreach (string name in q)
Console.WriteLine("Customer name = {0}", name);
Output:
Customer name = Koistya Navin
Customer name = RIA Guy
Reference: LINQ to XML