使用VB.Net XmlDocument.SelectNode方法读取XML文件将产生计数为零的结果



我是编码和XML文件的新手,正在尝试从XML文件中读取详细信息。这是我正在测试的一个示例文件:

<?xml version="1.0" standalone="yes"?>
<mailmanager xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<locations>
<store id="c35e549f-ffb8-4828-8290-d66c2f9b735f">
<type>msg</type>
<description>Volkswagen</description>
<folder>G:Volkswagen</folder>
</store>
<store id="814e7584-9f99-40a6-8520-3f5d467ea8d9">
<type>msg</type>
<description>Nissan</description>
<folder>G:Nissan</folder>
</store>
<store id="51d60458-01ac-421d-8fb8-3663f5963fbf">
<type>msg</type>
<description>Ford</description>
<folder>G:Ford</folder>
</store>
<store id="581d96c6-ea30-4301-b83b-d80473d18399">
<type>msg</type>
<description>Toyota</description>
<folder>G:Toyota</folder>
</store>
<store id="888eaace-9486-41db-a4ad-a21d570b0f35">
<type>msg</type>
<description>Tesla</description>
<folder>G:Tesla</folder>
</store>
<store id="44a6eaea-979c-4340-8a1d-1142507c42a0">
<type>msg</type>
<description>Fiat</description>
<folder>G:Fiat</folder>
</store>
</locations>
</mailmanager>

我发现,虽然我可以在调试中(使用Visual Studio(检查m_xmld,并且可以看到它将DocumentElement名称显示为";邮件管理器";,这似乎是正确的,对象m_nodelist的计数为零,因此跳过For Each循环中的代码。知道我哪里错了吗?

Private Sub LoadXMLToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoadXMLToolStripMenuItem.Click
Dim GUID As String
Dim sType As String
Dim sDescription As String
Dim sPath As String
Dim arr As String() = New String(3) {}
Dim arListItem As ListViewItem
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
''Create the columns for the listview
ListView1.Columns.Add("GUID", 600)
ListView1.Columns.Add("Description", 100)
ListView1.Columns.Add("Path", 70)
ListView1.View = System.Windows.Forms.View.Details
Application.DoEvents()
m_xmld = New XmlDocument
m_xmld.Load("c:temptesting2.xml")
'Get the list of name nodes 
m_nodelist = m_xmld.SelectNodes("/locations/store")
'Loop through the nodes
For Each m_node In m_nodelist
'Get GUID
GUID = m_node.Attributes.GetNamedItem("id").Value
'Get the Description Attribute Value
sDescription = m_node.ChildNodes.Item(1).InnerText
'Get the Path Element Value
sPath = m_node.ChildNodes.Item(2).InnerText

''Add a row to the listview
arr(0) = sType
arr(1) = sDescription
arr(2) = sPath
arListItem = New ListViewItem(arr)
ListView1.Items.Add(arListItem)
Application.DoEvents()
Next
End Sub

我建议使用XDocument而不是XmlDocument。您可以在此处找到文档:https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xdocument

然后,您可以通过调用Descendants方法来获得各种<store>元素:https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xcontainer.descendants

看看这个例子:

Dim m_xmld = XDocument.Load("testing2.xml")
Dim m_nodelist = m_xmld.Descendants("store")
For Each m_node In m_nodelist
ListView1.Items.Add(New ListViewItem({
m_node.Attribute("id").Value,
m_node.Element("description").Value,
m_node.Element("folder").Value
}))
Next

示例:https://dotnetfiddle.net/Kd8gQd

最新更新