为什么 getElementsByTagName 在 Visual Basic 中显示错误 "is not a member of 'XDocument"?

Why does getElementsByTagName shows error "is not a member of 'XDocument" in Visual Basic?

我一直在观看大量关于如何使用 Visual Basic 读取 XML 的视频,我相信我遵循的是正确的步骤,但我总是收到错误

BC30456 getElementsByTagName is not a member of 'XDocument'

这是我的代码:

Dim document As New XDocument
Dim nodoLista As XmlNodeList
Dim nodo As XmlNode

document = XDocument.Load(path)
nodoLista = document.getElementsByTagName("Empresa")

我已经在寻找替代品,也许代码是旧的并且已更新,但找不到任何东西,甚至没有类似的错误。我也试过 SelectNodes,但出现同样的错误。我还有 imports system.xml 顺便说一句。

也试过

nodoLista = document.Elements("Empresa")

但我收到错误

您实际上需要 Elements 方法:https://docs.microsoft.com/en-us/dotnet/api/system.xml.linq.xcontainer.elements

这是一个例子:

Dim xml = "<root><Empresa>1</Empresa><Empresa>2</Empresa><Empresa>3</Empresa></root>"
Dim document = XDocument.Parse(xml)
Dim root = document.Element("root")
Dim empresas = root.Elements("Empresa")

For Each empresa In empresas
     Console.WriteLine("Empresa: {0}", empresa.Value)
Next

Fiddle: https://dotnetfiddle.net/3THEAf

根据您的代码,您似乎想围绕 Xml.XmlDocument 而不是 Xdocument 进行编码,因为 getElementsByTagNameXml.XmlDocument 的函数( 或它的元素 descendatnts) which return a XmlNodeList 这是您的代码(已修改):

Dim document As New Xml.XmlDocument 
Dim nodoLista As Xml.XmlNodeList
Dim nodo As XmlNode

document.Load(path)
nodoLista = document.GetElementsByTagName("Empresa")