Jonny Wright
Jonny Wright

Reputation: 1119

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

Upvotes: 1

Views: 847

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

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.

Upvotes: 1

Related Questions