Search code examples
xmlvb.netparent-node

Don't process child nodes (Using "SelectNodes")


Example XML;

<root>
  <cmdset>Set 1
    <cmd>Command 1</cmd>
  </cmdset>
  <cmdset>Set 2
    <cmd>Command 2</cmd>
  </cmdset>
</root>

I only want to pull the text from within the <cmdset> tags. Example code;

Sub Main()
        Dim doc As XmlDocument = New XmlDocument()
        doc.Load("help.xml")
        For Each Element As XmlElement In doc.SelectNodes("//cmdset")
            Console.WriteLine(Element.InnerText)
        Next
        Console.Read()
    End Sub

Current output;

Set 1
    Command 1
Set 2
    Command 2

Desired output;

Set 1
Set 2

Thank you please


Solution

  • You would need to select just the text content using the XPath text() function, for instance:

    For Each textNode As XmlText In doc.SelectNodes("//cmdset/text()")
        Console.WriteLine(textNode.InnerText)
    Next
    

    Notice that I also changed the iterator from an XmlElement variable to an XmlText variable, since text content in an XML document is not considered to be element nodes, but rather text nodes.