如何从 vb.net 中的 xml 文档中获取元素名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14006965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:40:04  来源:igfitidea点击:

How to get element names from an xml document in vb.net

xmlvb.netvisual-studio-2010.net-4.0

提问by cMinor

I have a xml file like:

我有一个 xml 文件,如:

<config>
   <email  Host="201.0.0.0" From="[email protected]" Pass="xxx" Name="xxx"/>
   <gir    g1="Traditional" g2="mid Techn" g3="High Tech"/>
   <costs>
     <Pre-Incube    inscr="7000.00"  add="300.00"/>
     <Normal        inscr="1600.00"  inc="7000.00" add="500.00"/>
     <Urgent        inscr="1600.00"  inc="5000.00" add="500.00"/>
     <Estance       inscr="1600.00"  men="2500.00"/> 
     <Post          inscr="1600.00"  men="1500.00"/> 
   </costs>
</config>

To get the attributes for the element "gir" I do

要获取元素“gir”的属性,我会这样做

Dim doc As XmlDocument = New XmlDocument()
doc.Load(path)
Dim root As XmlNode = doc.DocumentElement         
Dim nodeGir As XmlNode = root.SelectSingleNode("/config/gir")
cboGir.Items.Add(nodeGir.Attributes.ItemOf("g1").InnerText)
cboGir.Items.Add(nodeGir.Attributes.ItemOf("g2").InnerText)
cboGir.Items.Add(nodeGir.Attributes.ItemOf("g3").InnerText)

But how do I get the namesof the child elements under "costs":

但是如何在“成本”下获取子元素的名称

Pre-Incube, Normal, Urgent, Estance, Post  

回答by RichardTowers

Adapted from this MSDN page:

改编自此MSDN 页面

Dim costs As XmlNode = root.SelectSingleNode("/config/costs")

Dim i As Integer 
For i = 0 To costs.ChildNodes.Count - 1
    cboGir.Items.Add(costs.ChildNodes[i].Name)
Next i

Or probably easier (from this MSDN page):

或者可能更容易(来自这个 MSDN 页面):

Dim costs As XmlNodeList = root.SelectNodes("/config/costs/*")
For Each book In costs      
    cboGir.Items.Add(book.Name)
Next 

Nameis a property on XmlNode- the docs are your friend.

NameXmlNode上的一个属性- 文档是您的朋友。

回答by Steven Doggart

To get the names of all the elements that are children of costs, you can do this:

要获取作为成本子项的所有元素的名称,您可以执行以下操作:

For Each node As XmlNode In doc.SelectNodes("/config/costs/*")
    cboGir.Items.Add(node.Name)
Next