2017-02-03 137 views
0

我正在從vb.net寫入XML文件。樣本看起來很像這樣。讀取XML子節點問題

<?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> 

我沒有問題寫它,但我有閱讀SavedMounts的子節點的問題。這是我到目前爲止,但不知道如何根據特定的ElementStrings拉特定的值。

這是我認爲代碼應該是這樣的,但需要一點幫助。

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 

任何想法?

+0

在messagebox.show以及你只是顯示的字符串。你打算從XML中顯示價值,然後你需要先閱讀它。 –

回答

1

使用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