需要根据子节点属性值提取xml文件的整个节点

时间:2013-03-05 06:38:34

标签: xml vb.net

这是我的xml:

<?xml version="1.0" encoding="utf-8"?>
<Tabel>
<Members>
  <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>
</Members>
</Tabel>

我的问题是我想提取整个成员节点,其中KD = 10.Plz帮助我如何做到这一点。 我使用vb.net作为编程语言

2 个答案:

答案 0 :(得分:0)

你可以使用Linq to XML和XDocument class:

来实现
Dim xml = XDocument.Load("myFilePath")
' or xml = XDocument.Parse("<Tabel> (...) </Tabel>") '

Dim myMember = xml.Root
                  .Element("Members")
                  .Elements("Member")
                  .First(Function(m) CInt(m.Element("KD")) = 10)

之后,myMember将成为与XElement元素对应的Member类实例。

答案 1 :(得分:0)

以下是您可以查看的两个示例。如果你真的不想使用LINQ,那么你需要学习XPath。

Sub Main()

    'This method uses the Xml DOM in the System.Xml namespace with XPath
    Dim xmlDoc = New XmlDocument()

    xmlDoc.Load("c:\test\test.xml")

    Dim membersNode As XmlNode = xmlDoc.DocumentElement.SelectSingleNode("/Tabel/Members")
    If membersNode IsNot Nothing Then
        Dim memberWithKDof10 As XmlNode = membersNode.SelectSingleNode("Member[KD = '10']")
        If memberWithKDof10 IsNot Nothing Then
            Console.WriteLine("Name of player with KD of 10 is {0}", memberWithKDof10.SelectSingleNode("Naam").InnerText)
        Else
            Console.WriteLine("Player not found!")
        End If
    End If


    'This method uses the XDocument classes found in the System.Xml.Linq namespace
    Dim xDoc As XDocument = XDocument.Load("c:\test\test.xml", LoadOptions.None)

    Dim membersElement As XElement = xDoc.Root.Element("Members")
    If membersElement IsNot Nothing Then
        Dim memberWithKDof10 As XElement = membersElement.Descendants("Member").FirstOrDefault(Function(e) e.Element("KD").Value = "10")
        If memberWithKDof10 IsNot Nothing Then
            Console.WriteLine("Name of player with KD of 10 is {0}", memberWithKDof10.Element("Naam").Value)
        Else
            Console.WriteLine("Player not found!")
        End If
    End If

    Console.WriteLine()
    Console.WriteLine("Press ENTER to exit...")
    Console.ReadLine()
End Sub