searching for a specific value in xml nodes

mjd430

Member
Joined
Feb 28, 2007
Messages
6
Programming Experience
Beginner
Hello,

I have an XML file and there is one node, <NODE1>. that has several child nodes.
I want to loop through each child node, <NODE2>, and get the value of <NODEB>.
I want to find which child node, <NODE2>, has a child node, <NODEB>, that equals "ROOF". Once I find the <NODE2> that contains the <NODEB> that equals "ROOF", I want to restart the loop so that I can evaluate each child node in that <NODE2>. See sample XML below.

Is there anyway to restart a loop? I'm new to evaluating XML in VB.net, so I don't
know if there is anyway to search a group of nodes looking for a specific value.


HTML:
<NODE1>
  <NODE2>
    <NODEA>1</NODEA>
    <NODEB>FLOOR</NODEB>
    <NODEC>WOOD</NODEC>
  <NODE2>
  <NODE2>
    <NODEA>2</NODEA>
    <NODEB>ROOF</NODEB>
    <NODEC>SHINGLE</NODEC>
  <NODE2>
  <NODE2>
    <NODEA>3</NODEA>
    <NODEB>SIDING</NODEB>
    <NODEC>SHINGLE</NODEC>
  <NODE2>
<NODE1>
 
Last edited by a moderator:
That is not valid xml, but perhaps you just typed it off hand?
You can use Xpath to select the node, also given that clause, for example (given valid xml):
VB.NET:
Dim doc As New Xml.XmlDocument
doc.Load("roof.xml")
Dim xpath As String = String.Format("/NODE1/NODE2[NODEB='{0}']", "ROOF")
Dim node2 As Xml.XmlNode = doc.SelectSingleNode(xpath)
I recommend Xpath tutorials to learn more about that.
 
In the off chance that you're using a version of .NET greater than 2.0 here's an example using LINQ.

VB.NET:
        Dim nodeSearchTerm = "ROOF"
        Dim q = (From n In XDocument.Load("C:\Temp\nodes.xml").Descendants
                   Where n.<NODEB>.Value = nodeSearchTerm).FirstOrDefault

        If q Is Nothing Then
            MessageBox.Show(String.Format("NODEB Value: {0} not found", nodeSearchTerm))
        Else
            MessageBox.Show(q.ToString)
        End If
 
Thanks JohnH. I finally got around to this after being sidetracked and I did as you suggested and it works perfectly. Thanks!
 
Back
Top