• 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
https://www.neowin.net/forum/topic/186897-vbnet-reading-xml-files/
Share on other sites

22 answers to this question

Recommended Posts

  • 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

  • 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.

  • 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

  • 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.

  • 0
  Tom Servo said:
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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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

  • 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

  • 0
  ChocIST said:
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.

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

    • No registered users viewing this page.
  • Posts

    • Explzh 9.81 by Razvan Serea Explzh is a free Windows archive manager for creating, extracting and managing archives. The program supports many different types of archives, including zip, 7z, rar, tar, ace, lzh, arj, cab, iso, img, msi, sfx and more. Apart from archive creation and extraction, you will also be able to verify compressed data for errors, initiate repair routines, split data into multiple items, and more. It additionally allows you to password protect your data and attach digital signatures to files. Key features of Explzh: Explorer-like GUI and operability. LHA, ZIP (ZIPX), JAR, CAB, RAR, TAR, TAR.XXX, 7z, ARJ, WIM, CHM, PE, HFS, NSIS Format Installer, ISO, InstallShield, MSI, and several other formats... Support for more archive formats by introducing the integrated archiver DLL. Self-extracting archive creation function that can create high-performance automatic installers. Digital signature addition function to created self-extracting archive. Office 2007 or later document compression / image optimization re-archiving function. Supports compression and decompression of Unicode file names. Supports compression and expansion exceeding 4GB. AES encryption function. You can create a robust secure ZIP encryption archive. Thumbnail function of image file. In-library file search function. . Equipped with archive file conversion function. File split function. The split file has a self-consolidation function, and can concatenate files larger than 4GB. (No need for batch file or connection software) UU (XX) Encode, Base64 decode function. FTP upload function Supports Windows 11 shell integration extended context menu. Explzh 9.81 changelog: Improved to send update notifications to the shell when making changes such as additional compression to existing zip and 7-zip files. This also updates the Explorer view of the open file in real time. (If the drop target feature is enabled, you can easily create an encrypted ZIP by dragging and dropping onto the ZIP icon while holding down the Ctrl key.) When the zip drop target setting is enabled, the "Compressed (zipped) Folder" item will be added to the "New" shell context menu if it does not already exist. Password manager bug fix: Fixed a bug that caused the app to crash when reading password.dat (password data) when changing authentication method. Updated to Visual Studio 2022 v.17.14.9. Download: Explzh 64-bit | Explzh 32-bit | ~6.0 MB (Freeware) Download: Explzh ARM64 | 5.9 MB View: Explzh Home Page | Screenshot | Themes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Have to get that indoctrination in early I guess
    • The reason why I'm using as much portable software as possible.
    • Personally, I used to be a big fan of the Evo drives but have found the Corsair MP 700 is just a bit faster and seems to fit my needs just as well. 
  • Recent Achievements

    • One Month Later
      Johnny Mrkvička earned a badge
      One Month Later
    • Week One Done
      Sender88 earned a badge
      Week One Done
    • Dedicated
      Daniel Pinto earned a badge
      Dedicated
    • Explorer
      DougQuaid went up a rank
      Explorer
    • One Month Later
      MIghty Haul earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      605
    2. 2
      Michael Scrip
      200
    3. 3
      ATLien_0
      191
    4. 4
      +FloatingFatMan
      138
    5. 5
      Xenon
      127
  • Tell a friend

    Love Neowin? Tell a friend!