读取XML子节点问题

时间:2017-02-03 22:28:10

标签: xml vb.net

我正在从vb.net写入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

有什么想法吗?

1 个答案:

答案 0 :(得分: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