如何从XML文件中的特定节点获取值?

时间:2012-05-23 18:33:19

标签: xml vb.net linq xpath xml-serialization

从这个XML代码:

<?xml version="1.0" encoding="utf-8"?>
<Tabel>
  <Member>
    <Naam>Cruciatum</Naam>
    <Kills>1000</Kills>
    <Deaths>10</Deaths>
    <KD>100</KD>
  </Member>
  <Member>
    <Naam>Ghostbullet93</Naam>
    <Kills>10</Kills>
    <Deaths>1</Deaths>
    <KD>10</KD>
  </Member>
</Tabel>

如何获得(例如)<Kills>旁边的10?

我尝试过多次没有成功的事情。 我的一个想法就是使用这段代码:

Dim doc = XDocument.Load("C:\members.xml")
        Dim members = From m In doc.Element("Tabel").Elements("Member")
                      Select naam = m.Element("Naam").Value
        For Each member In members
            lstmembers.Items.Add(member)
        Next

但是我无法弄清楚如何编辑该代码段以使我现在需要它。

(以上代码适用于使用它的地方。)

2 个答案:

答案 0 :(得分:10)

您还可以使用XPath来读取元素的值:

Dim doc As XmlDocument = New XmlDocument()
doc.Load("C:\members.xml")
Dim kills As String = doc.SelectNode("Tabel/Member[Naam='Ghostbullet93']/Kills").InnerText

但是,如果您打算加载和使用所有数据,那么使用序列化会容易得多。要做到这一点,首先需要创建模仿XML结构的类(为简单起见,我只使用公共字符串字段,但最好使用属性):

Public Class Member
    Public Naam As String
    Public Kills As Integer
    Public Deaths As Integer
    Public KD As Integer
End Class

Public Class Tabel
    <XmlElement("Member")> _
    Public Members As List(Of Member)
End Class

然后像这样反序列化XML:

Dim serializer As XmlSerializer = New XmlSerializer(GetType(Tabel))
Dim tabel As Tabel = CType(serializer.Deserialize(File.OpenRead("C:\members.xml")), Tabel)
For Each member As Member in tabel
    Dim kills As Integer = member.Kills
Next

答案 1 :(得分:3)

Steve推荐的

XPathXmlDeserialization是很好的选择,但对于纯LINQ解决方案,您只需要在查询中添加适当的Where子句。

Dim doc = XDocument.Load("C:\members.xml")
Dim members = From m In doc.Element("Tabel").Elements("Member")
              Where m.Element("Naam").Value = "Ghostbullet93"
              Select kills = m.Element("Kills").Value
在此示例中,

members仍然是IEnumerable<String>,因此如果您只有1个对象,则需要执行以下操作:

Dim member = members.First()  // will throw exception if collection is empty

Dim member = members.Single()  // will throw exception if collection is empty or has 2 or more elements

(我的vb.NET非常生疏,所以请原谅任何语法错误。)