xmlvb.netxmlnodelist

Browse through nodes in XmlNodeList (vb.net)


I can't find in the documentation how to "browse" through the nodes that I already have in XmlNodeList.

Given this XML:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE tmx SYSTEM "tmx14.dtd">
<tmx version="1.4">
  <tu changedate="20180509T145123Z" creationdate="20180509T145123Z" >
    <prop type="aligned">no</prop>
    <prop type="x-context">320920</prop>
    <tuv xml:lang="en-gb">
      <seg>Hello1</seg>
    </tuv>
    <tuv xml:lang="es">
      <seg>Hola1</seg>
    </tuv>
  </tu>
  <tu changedate="20180509T145216Z" creationdate="20180509T145216Z" >
    <prop type="aligned">no</prop>
    <prop type="x-context">325152</prop>
    <tuv xml:lang="en-gb">
      <seg>Hello2</seg>
    </tuv>
    <tuv xml:lang="es">
      <seg>Hola2</seg>
    </tuv>
  </tu>
</tmx>

I am trying to run through the different nodes in each /tu to load that to a DB. Should be simple but I am struggling with the syntax.

So far I have this:

Dim tmxfile As String = "d:\Documents\Desktop\myxml.xml"
        Dim xmldoc As New XmlDocument
        xmldoc.Load(tmxfile)

        Dim nodes As XmlNodeList = xmldoc.DocumentElement.SelectNodes("//tu")

        For node = 0 To nodes.Count - 1
            Dim x = nodes.Item(node).SelectNodes("/seg")

            MsgBox(x.ToString)
        Next
    End Sub

What I am trying to achieve is to show each /seg in //tu. The first part of the code is fine as if I loop through node with innerxml or innertext I see the actual elements of XML, but I am struggling to get the specified elements on those nodes.

Any guidance?

Thanks in advance!


Solution

  • If you'd use XDocument instead of XmlDocument, you could use unique VB's feature - XML Literals:

    Sub Main()
    
        Dim xml =
    <?xml version="1.0" encoding="utf-8"?>
    <tmx version="1.4">
        <tu changedate="20180509T145123Z" creationdate="20180509T145123Z">
            <prop type="aligned">no</prop>
            <prop type="x-context">320920</prop>
            <tuv xml:lang="en-gb">
                <seg>Hello1</seg>
            </tuv>
            <tuv xml:lang="es">
                <seg>Hola1</seg>
            </tuv>
        </tu>
        <tu changedate="20180509T145216Z" creationdate="20180509T145216Z">
            <prop type="aligned">no</prop>
            <prop type="x-context">325152</prop>
            <tuv xml:lang="en-gb">
                <seg>Hello2</seg>
            </tuv>
            <tuv xml:lang="es">
                <seg>Hola2</seg>
            </tuv>
        </tu>
    </tmx>
    
        xml.AddFirst(New XDocumentType("tmx", "SYSTEM", "tmx14.dtd", ""))
    
        ' All <tu> elements
        Dim tus = xml.<tmx>.<tu>
    
        For Each tu In tus
            Dim seg = tu.<tuv>.<seg>
            Console.WriteLine(seg.Value)
        Next
    
        Console.ReadKey(True)
    
    End Sub