[.net] Reading XML

Started by
5 comments, last by Sijmen 19 years, 6 months ago
Hi there! I would like to read an XML file, for example:

<?xml version="1.0">
<books>
 <book>
  <title>.NET For Dummies</title>
  <author>Doc. Net</author>
 </book>
 <book>
  <title>XML For Dummies</title>
  <auther>C.U. There</author>
 </book>
</books>

The problem is, I don't know how to parse it. This is how I would love it:

XMLReader reader = new XMLReader(fileStreamOfXmlFile);
Node[] top = reader.GetTopNode().GetNodes("book");

foreach(Node book in top)
{
	Console.WriteLine("Title:  {0}", book.GetNodes("title")[0];
	Console.WriteLine("Author: {1}", book.GetNodes("author")[0];
}

Do such classes exist in the .NET Framework? There are so many classes that I can't see the wood trough the trees. If there aren't such classes, what would be the best other way to do such parsing? Thanks beforehand!
Advertisement
I generally load the document into an XmlDocument and parse that.

XmlDocument xmlDoc = New XmlDocument();xmlDoc.Load( "yourfilename.xml" );XmlElement xmlRoot = xmlDoc.DocumentElement;XmlNodeList xmlBookNodes = xmlRoot.GetElementsByTagName("book");foreach (XmlElement xmlBook in xmlBookNodes){ // Do your stuff}


I've not used XmlReaders much so my way makes sense to me and works pretty well for my needs. But then, there's always so many ways to skin a cat in .NET.
Hey, awesome, just what I need.
Thanks!
I would make an xml schema and a dataset that is typed to the xml schema. I would then use an xmlreader with my dataset to read the elements.
Yup. I think xGoblin's got it right. There's even a snazzy integrated way of doing it (in Visual Studio) that involves little coding. Create an XML "Schema" and turn on GenerateDataset. It will generate a nice class for you that will load an XML file using that schema.
Co-creator of Star Bandits -- a graphical Science Fiction multiplayer online game, in the style of "Trade Wars'.
Quote:Original post by The Frugal Gourmet
Yup. I think xGoblin's got it right. There's even a snazzy integrated way of doing it (in Visual Studio) that involves little coding. Create an XML "Schema" and turn on GenerateDataset. It will generate a nice class for you that will load an XML file using that schema.


I don't think I did any coding. I made the xml schema in the editor, and then on the .aspx page, I dragged a dataset over it, told it to make it a typed dataset in the drop-down menu (specifying the correct type of course), and then calling the readXML function, which is basically the only coding I had to do.
To clarify this a bit more: this is about reading RSS feeds.

This topic is closed to new replies.

Advertisement