PapaBless PapaBless - 11 days ago 5
Vb.net Question

Search inside XML file and get sibling nodes

I have and Xml file that contains

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

<?xml version="1.0" encoding="utf-8"?>
<FileChecksums>
<file>
<filepath>930cdc93-5df2-4262-ba31-824e83404a2c.jpg</filepath>
<checksum>C4D9F0D47FF88130ABF0DA3C5351D71938C705F6602AE412D946AD5C74850837</checksum>
</file>
<file>
<filepath>7dd01bb9-3f35-442c-8840-1540632973f3.png</filepath>
<checksum>27EA8D4378DC8DB92F3D9ADA887E124BECAED47816FD3FFE49A4027362AF0FDC</checksum>
</file>
</FileChecksums>


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

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

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

Answer

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.

Example:

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
    Debug.WriteLine(xFile.<filepath>)
End If

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

Comments