PapaBless PapaBless - 1 year ago 61 Question

Search inside XML file and get sibling nodes

I have and Xml file that contains

and its
. I want to get its
. This is the sample xml file:

<?xml version="1.0" encoding="utf-8"?>

If there's a match at the
's inner text, I would like to get the corresponding
's inner text.

This is the code: (It will only read all tag)

Private Sub LocateFromChecksum(chksum As String)
Dim xmlDoc As New XmlDocument()
'search here?
For Each node As XmlNode In xmlDoc.DocumentElement.SelectSingleNode("checksum")
End Sub

Answer Source

Use the mighty Linq-to-Xml.

It has some nice syntactic sugar for VB .NET, e.g. you can access xml-elements with angle brackets: <filepath>.

Also, as the name suggest, you can simply use linq to filter your xml.


Dim x As XDocument = XDocument.Load("checksum.xml")
Dim sampleChecksum = "27EA8D4378DC8DB92F3D9ADA887E124BECAED47816FD3FFE49A4027362AF0FDC"

Dim xFile = x.<FileChecksums>.<file>.Where(Function(c) c.<checksum>.Value = sampleChecksum)
'Or even (same result)':
xFile = x...<file>.Where(Function(c) c.<checksum>.Value = sampleChecksum)

If xFile.Any() Then
End If

You can even omit the .Value in the last line since there exist some built-in value conversions for XElements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download