TonyW
TonyW

Reputation: 786

Reading XML child nodes issue

I'm writing to a XML file from vb.net. A sample would look much like this.

<?xml version="1.0" encoding="utf-8"?>
    <Settings>
      <LaunchOnReboot>True</LaunchOnReboot>
      <SavedMounts>
        <Mount>
          <Description>fake mount</Description>
          <DriveLetter>B</DriveLetter>
          <DriveLocation>\\Location\1</DriveLocation>
          <UserName>User</UserName>
          <Password>FakePassword2</Password>
          <AutomagicallyMount>False</AutomagicallyMount>
          <Linux>True</Linux>
        </Mount>
        <Mount>
          <Description>fake mount 2</Description>
          <DriveLetter>G</DriveLetter>
          <DriveLocation>\\fake\fakelocation</DriveLocation>
          <UserName>awiles</UserName>
          <Password>FakePassword</Password>
          <AutomagicallyMount>False</AutomagicallyMount>
          <Linux>True</Linux>
        </Mount>
      </SavedMounts>
    </Settings>

I have no problem writing it, but i'm having an issue reading the SavedMounts childnodes. This is what i'm coming up with so far, but not sure how to pull specific values based on specific ElementStrings.

This is how I think the code should look like, but need a little help.

 Dim node As XmlNode
 node = doc.DocumentElement.SelectSingleNode("SavedMounts")
 If node.HasChildNodes Then
    For Each child As XmlNode In node.ChildNodes
       For Each child2 As XmlNode In node.ChildNodes
            Messagebox.show("Description")
            Messagebox.show("DriveLetter")
            Messagebox.show("DriveLocation")
            Messagebox.show("UserName")
            Messagebox.show("Password")
            Messagebox.show("AutomagicallyMount")
            Messagebox.show("Linux")
       Next
    Next
 End If

Any ideas?

Upvotes: 1

Views: 211

Answers (1)

jdweng
jdweng

Reputation: 34421

Using xml linq :

Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)

        Dim results = doc.Descendants("Mount").Select(Function(x) New With { _
            .description = CType(x.Element("Description"), String), _
            .driveLetter = CType(x.Element("DriveLetter"), String), _
            .driveLocation = CType(x.Element("DriveLocation"), String), _
            .userName = CType(x.Element("UserName"), String), _
            .password = CType(x.Element("Password"), String), _
            .automagicallyMount = CType(x.Element("AutomagicallyMount"), String), _
            .linux = CType(x.Element("Linux"), Boolean) _
        }).ToList()
    End Sub

End Module

Upvotes: 1

Related Questions