Visual Basci XML how to find a parent element name?

Havooma 156 Reputation points
2022-05-09T19:06:37.077+00:00

I have an xml file that looks like this:

<?xml version="1.0" encoding="utf-8"?>
<times>
<transfer1>
<given type="type1">
<data1>"data1 here</data1>
<data2>"data2 here"</data2>
</given>
<given type="type2">
<data1>"data1 here</data1>
<data2>"data2 here"</data2>
</given>
</transfer1>
<transfer2>
<given type="type3">
<data1>"data1 here</data1>
<data2>"data2 here"</data2>
</given>
</transfer2>
</times>

I have been give the name of the "type" (lets say the given type = "type2") but want to then know the parent node. In this case it would be "transfer1". Ive looked everywhere and tried many things but cant seem to find what I need. Are there any ideas on how to do this in VB?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,657 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 25,726 Reputation points
    2022-05-09T19:58:45.767+00:00

    Hi @Havooma ,

    Please try the following solution.
    It is using LINQ to XML API.
    It is available in the .Net Framework since 2007.

    VB.NET

    Sub Main  
     Const inputFile As String = "e:\Temp\Havooma.xml"  
     Dim xdoc As XDocument = XDocument.Load(inputFile)  
      
     Dim xmlNode As String = xdoc.Descendants("given") _  
     .Where(Function(x) x.Attribute("type").Value.Equals("type1")) _  
     .FirstOrDefault()?.Parent.Name.ToString()  
      
     Console.Write(xmlNode)  
    End Sub  
    

    Output

    transfer1  
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Viorel 114.4K Reputation points
    2022-05-09T20:08:08.793+00:00

    If you are using XmlDocument, then:

    Imports System.Xml
    Imports System.Security
    . . .
    Dim doc As New XmlDocument
    doc.Load("MyFile.xml")
    Dim type As String = "type2"
    
    Dim result As XmlNode = doc.SelectSingleNode($"/times/*[given[@type='{SecurityElement.Escape(type)}']]")
    
    If result IsNot Nothing Then
        Console.WriteLine(result.OuterXml)
    Else
        Console.WriteLine("Not found")
    End If
    
    1 person found this answer helpful.
    0 comments No comments

  2. Viorel 114.4K Reputation points
    2022-05-09T19:57:28.24+00:00

    Try an example:

    Dim doc As XDocument = XDocument.Load("MyFile.xml")
    Dim type As String = "type2"
    
    Dim result As XElement = (From t In doc.<times>.Elements
                                From g In t.<given>
                                Where g.@type = type
                                Select t).FirstOrDefault
    
    If result IsNot Nothing Then
        Console.WriteLine(result)
    Else
        Console.WriteLine("Not found")
    End If
    
    0 comments No comments