I created the following procedure a while ago, and decided to share it, because I'm fairly proud of it. I wrote it to grab the user's default font settings from the SAP configuration file, but I think it could be used to parse virtually any XML file and extract just the information that we need from it.
''' <summary> ''' Searches within an XML file, through specific elements, for a specific attribute that has a specific value. ''' If we find the attribute that has a specific value that we desire, then we return the text value of that node ''' </summary> ''' <param name="sInputFile">Input file name</param> ''' <param name="sElementsToSearch">String of the element tags that we want to search through</param> ''' <param name="sAttributeToSearchFor">String of the name of the attribute that the element must contain</param> ''' <param name="sAttrValToSearchFor">String of the value of the attribute that the element must contain</param> ''' <returns>Returns the sought after value on success, Nothing on failure</returns> ''' <remarks></remarks> Private Function searchXMLFile(ByVal sInputFile As String, ByVal sElementsToSearch As String, ByVal sAttributeToSearchFor As String, ByVal sAttrValToSearchFor As String) As String Try Dim xmlReader As XmlTextReader = New XmlTextReader(sInputFile) Dim blnFoundAttribute As Boolean = False
'Continue while there's something to read Do While (xmlReader.Read())
'Determine what aspect of a node this is Select Case xmlReader.NodeType
Case XmlNodeType.Element 'The beginning tag of an element
'Skip the element if it's not one of the elements that we want to search in If xmlReader.Name.IndexOf(sElementsToSearch) = -1 Then Continue Do End If
If xmlReader.HasAttributes Then 'If attributes exist
'Enumerate through all of the attributes, one by one until we find the desired attribute While xmlReader.MoveToNextAttribute() AndAlso Not blnFoundAttribute
'This queries the "name" of the attribute If xmlReader.Name.IndexOf(sAttributeToSearchFor) = -1 Then Continue While Else 'Check the "value" of the attribute and ensure that it matches what we're looking for If xmlReader.Value.IndexOf(sAttrValToSearchFor) = -1 Then Continue While Else blnFoundAttribute = True Exit While End If End If End While End If Case XmlNodeType.Text 'The text value within an element
'If we found the attribute that we were searching for, then this value must be the value that we want to return If blnFoundAttribute Then Return xmlReader.Value End If
Case XmlNodeType.EndElement 'Display the end of the element 'The end tag of the element End Select Loop
'If we got here, then we didn't find what we are looking for, return nothing Return Nothing
Catch ex As Exception MsgBox("Error in procedure " & System.Reflection.MethodInfo.GetCurrentMethod.Name.ToString & ": " & ex.Message.ToString) Return Nothing End Try End Function