0

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 "http://java.sun.com/dtd/preferences.dtd">
<preferences EXTERNAL_XML_VERSION="1.0">
  <root type="system">
    <map/>
    <node name="Level1">
      <map/>
      <node name="current">
        <map/>
       <node name="PublicIdentity">
          <map>
            <entry key="PublicAddresses[PRIMARY][0]" value="192.168.1.1"/>
            <entry key="PublicAddresses[SECONDARY][0]" value="192.168.1.2"/>
          </map>
        </node>
      </node>
    </node>
  </root>
</preferences>

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
    XmlDoc.Load("prefs.xml")
    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
        Next
    Next
End Sub

End Module

1 Answer 1

0

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

Solution

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)
        Console.WriteLine(primaryIPAddress)
    End If
    If secResult IsNot Nothing Then
        Dim secondaryIPAddress = CType(secResult.Attribute("value"), String)
        Console.WriteLine(secondaryIPAddress)
    End If
End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.