sIKE sIKE - 8 months ago 50 Question

Retrieve XML attribute value based on previous attribute value VB.Net

I am trying to retrieve the attribute "value" if "key" = PublicAddresses[PRIMARY][0]. I am very new at this and I am trying to learn VB.Net as I go.

Here is my xml document layout

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE preferences SYSTEM "">
<preferences EXTERNAL_XML_VERSION="1.0">
<root type="system">
<node name="Level1">
<node name="current">
<node name="PublicIdentity">
<entry key="PublicAddresses[PRIMARY][0]" value=""/>
<entry key="PublicAddresses[SECONDARY][0]" value=""/>

Here is what I have come up with, very spaghetti like:

Imports System
Imports System.Xml
Module Module1

Sub Main()
Dim XmlDoc As XmlDocument = New XmlDocument
For Each Element As XmlElement In XmlDoc.SelectNodes("//*")
For Each Attribute As XmlAttribute In Element.Attributes
If Attribute.Name = "value" Then
Console.WriteLine("{0}", Attribute.Value)
End If
End Sub

End Module


Using google to search StackOverflow I was able to find this gem:


and here is my solution:

Sub Main()
    Dim doc As XElement = XElement.Load("prefs.xml")
    Dim primaryKey = "PublicAddresses[PRIMARY][0]"
    Dim secondaryKey = "PublicAddresses[SECONDARY][0]"
    Dim priResult = doc.Descendants("entry").Where(Function(user) CType(user.Attribute("key"), String) = primaryKey).SingleOrDefault
    Dim secResult = doc.Descendants("entry").Where(Function(user) CType(user.Attribute("key"), String) = secondaryKey).SingleOrDefault

    If priResult IsNot Nothing Then
        Dim primaryIPAddress = CType(priResult.Attribute("value"), String)
    End If
    If secResult IsNot Nothing Then
        Dim secondaryIPAddress = CType(secResult.Attribute("value"), String)
    End If
End Sub