2017-02-03 101 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