• 0

[VB.NET] Reading XML Files


Question

I want to be able to read an XML file which contains configuration details for the application, called settings.xml

<configuration>
 <setting name="servers">server</setting>
 <setting name="port">1234</setting>
</configuration>

How would i be able to read something like that using VB.NET?

ChocIST

Link to comment
Share on other sites

22 answers to this question

Recommended Posts

  • 0

there's a couple of ways to do it. you could use either XmlTextReader(XmlReader) or XmlDocument classes.

the easiest is to use XmlDocument.

Link to comment
Share on other sites

  • 0

Here's an example, although I've taken the liberty of altering your XML data structure a little bit. I'm guessing you want to be able to store/load multiple servers so this structure would probably work best:

<configuration>

<server name="server1" port="1234"/>

<server name="server2" port="1234"/>

</configuration>

Dim xmlSettings As New Xml.XmlDocument

xmlSettings.Load(Application.StartupPath & "\settings.xml")

Dim xmlServers As Xml.XmlNodeList = xmlSettings.DocumentElement.SelectNodes("server")

Dim PrototypeServer As Server

Dim x As Integer

For x = 0 To xmlServers.Count - 1

PrototypeServer.Name = xmlServers(x).Attributes("name").Value

PrototypeServer.Port = xmlServers(x).Attributes("port").Value

Servers.Add(PrototypeServer)

Next

Link to comment
Share on other sites

  • 0

Just a FYI, the example above is a simplistic example. You need additional code to probe for the existance of the attributes before reading them out. The missing of either port and/or name attributes would cause an exception to be thrown in the example above. Same applies to loading the XML and selecting the server nodes.

Link to comment
Share on other sites

  • 0

That depends upon what you are wanting to do. XmlReader provides forward- and read-only access to the XML document. If all you need to do is pull the settings from the XML document, this would be your best bet.

If you want to have full access to the XML document, go with XmlDocument. You'll be able to pull information from any node at will, change data, etc.

I would leave behind some code, but I don't know any VB.NET (I'm a C# lover). I can, however, point you to some MSDN documents.

XmlReader

XmlDocument

Link to comment
Share on other sites

  • 0

I'd suggest XmlDocument. An XmlReader would introduce loads of code around it to read out the XML file. Since it's a settings file, I assume there will be other stuff in there than just two lines that define a server. Selecting nodes from an XmlDocument would be favorable over a parser to be written around the XmlReader. Trust me, it ain't fun at all, I've experience with parsing XML streams thanks to that XMPP pet project of mine.

Link to comment
Share on other sites

  • 0
I'd suggest XmlDocument. An XmlReader would introduce loads of code around it to read out the XML file. Since it's a settings file, I assume there will be other stuff in there than just two lines that define a server. Selecting nodes from an XmlDocument would be favorable over a parser to be written around the XmlReader. Trust me, it ain't fun at all, I've experience with parsing XML streams thanks to that XMPP pet project of mine.

You would still have to have loads of code going the XmlDocument route. You'll still have to select the nodes you wanted to check (which is basically parsing through the document). Either way, there's going to be many lines of code to get the information you want.

Link to comment
Share on other sites

  • 0

Not really. A switch...case block would work beautifully. It may be more lines, but it certainly isn't the trainwreck you paint the picture to be. But then again, I'm talking from a C# point of view; VB may require stuff that I am not aware of.

Link to comment
Share on other sites

  • 0

There needs to be more plumbing than a simple switch...case block. I've a whole XmlReader based parser for the Jabber protocol, and it's indeed a trainwreck, and I'm not exactly delighted, since I've barely implemented any of the JEPs. And it's written in C# too. Creating tool functions to manage safe and proper navigation brings back a bit elegancy, but it's still not that nice.

Link to comment
Share on other sites

  • 0

For something this simple, though, it wouldn't be that much of a problem. From the XML excerpt he's given us, it's the same element name, just different attributes. The switch would be the value of the name attribute, and he could get whatever data he needed. It's a simple solution for a simple XML document.

If his XML document was more complex with different elements and attributes or if he needed to make changes to the document through the code, I would understand going with XmlDocument. In this case, however, I still recommend the XmlReader approach.

Nice site, btw.

Link to comment
Share on other sites

  • 0

I'm assuming the snippet above is just an example and expect the config file to be larger in real use. Also he seems to be a newbie to the XML parsing stuff, pestering him with XmlReader is just nasty, especially since as newbie he'll probably wonder why the case block gets fired twice, as I did until I realized few secs later that closing tags are handled as seperate elements too, just to name one of the quirks you could avoid with XmlDocument.

And about the site, thanks.

Link to comment
Share on other sites

  • 0

It all depends upon the complexity of the config file. As I said before, if it is more complex than the above, then use XmlDocument. If it's not (and it's just as simple as the snippet he gave) go with XmlReader. It really isn't pestering, as it is very simple:

private void Foo() 
{
     string port = "";
     string servers = "";
     XmlTextReader settingsDoc = new XmlTextReader("settings.xml");
 ?	
     while (settingsDoc.Read()) 
     {
               switch(settingsDoc.GetAttribute("name")) 
               {
                    case "servers":
                         servers = settingsDoc.ReadInnerXml();
                    break;
                    case "port":
                         port = settingsDoc.ReadInnerXml();
                    break;
                    default:
                    break;
               }
     }
}

Going with XmlDocument isn't any easier (or harder). If he's a XML newbie, then he needs to know how to do it both ways, and know in which instance to use which class. For a simple XML document, use XmlReader. For a complex XML document, use XmlDocument.

Link to comment
Share on other sites

  • 0

XmlSerialization could be good for this if you know the structure of the xml file. It will probably be the easiest of the methods mentioned above once you get the hang of it.

Dan

Link to comment
Share on other sites

  • 0

Thank you all for replying to my question, this problem has now been solved with code taken from above.

Thank You All

ChocIST

Link to comment
Share on other sites

  • 0

Hi There,

If your trying to read values from a XML config file then this is really easy . . .

Click the project menu, select add component and then add an application.config file to your project.

The application.config file would look like something like this . . .

&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
   &lt;appSettings&gt;
      &lt;add key="timerint" value="300000" /&gt;
      &lt;add key="filepath" value="e:/music/MP3/" /&gt;
      &lt;add key="person" value="andy" /&gt;
   &lt;/appSettings&gt;
&lt;/configuration&gt;

you then use the following code to extract the keys into strings so that you can use them in your program . . .

Dim timerint As Integer
Dim filepath As String
Dim person As String

timerint = ConfigurationSettings.AppSettings("timerint")
filepath = ConfigurationSettings.AppSettings("filepath")
person = ConfigurationSettings.AppSettings("person")

Thats how you do an extremly simply config file for your project.

I hope that helps. :happy:

Kind Regards

Link to comment
Share on other sites

  • 0

Ahh now I know what you want, well I used to think the document way was easier but over the last few weeks I have taught myself how to manipulate XML files with datasets, so . . .

Datasets in my personal view is the easiest way to manipulate XML files ! :yes:

Here's an example from one of my projects that reads a xml file into a dataset adds a row and then writes it back to the XML file :

' Read data from xml file

Dim ds As New DataSet
ds.ReadXml("data.xml")
Dim dt As DataTable = ds.Tables("questions")

' Add Row

Dim row As DataRow
row = dt.NewRow()
row("question") = question.SelectedItem
row("answer") = answer.Text
dt.Rows.Add(row)

' Write data back to xml file

ds.WriteXml("data.xml")

I hope thats helps answer ya question, LOL ! :happy:

Kind Regards

Link to comment
Share on other sites

  • 0

That looks alot easier then the looping code earlier.

ChocIST

Link to comment
Share on other sites

  • 0
That looks alot easier then the looping code earlier.

ChocIST

Yeah its much easier, datasets are great !

You can extract just the data you want alot easier with a dataset because once you have put an XML file into a dataset you can INSERT, UPDATE and DELETE just like an SQL database and then with one command write the your changes back to the XML file.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.