Question How to Get Inner Text of XML

digitaldrew

Well-known member
Joined
Nov 10, 2012
Messages
167
Programming Experience
Beginner
Hey everyone..I have an XML file which contains three different domains in it. What I am trying to do is read the Descendants portion to find a specific code. If that code is "200" then I want to pull the innertext between the >< of that node. I'm about to read the descendants just fine but I'm having problems getting the innertext of that same node..

Here is what the XML would look like
HTML:
<?xml version="1.0" encoding="UTF-8"?>
<Transaction>
<request>check</request>
<ip>192.168.0.1</ip>
<domain code="200">ABC.com</domain>
<domain code="506">BCD.com</domain>
</Transaction>

and here is my code so far..
VB.NET:
        Dim XML_Code As String = checkResponse
        Dim document As XDocument = XDocument.Parse(XML_Code)
        Dim my_domains = document.Descendants("Transaction").Descendants("domain")
        If my_domains.Count > 0 Then
            For Each my_domain As XElement In my_domains
                If my_domain.Attribute("code").Value = 200 Then
                    'HERE IS WHERE I WANT TO GET THE INNERTEXT OF THAT NODE
                Else
                    'do something else
                End If
            Next
        End If

As you can see above..when the attribute equals 200 such as the first domain node in my example..I then want it to pull the <domain></domain> innertext..Otherwise, if it throws something else such as 506 in my second example - it will do something else..
 
Hi,

Here are two ways that this can be done:-

VB.NET:
Imports System.IO
Imports System.Xml
 
Public Class Form1
  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Using myReader As New StreamReader(Application.StartupPath & "\XMLFile1.xml")
      Dim xmlDoc As New XmlDocument
 
      xmlDoc.LoadXml(myReader.ReadToEnd)
      For Each XNode As XmlNode In xmlDoc.GetElementsByTagName("domain")
        If XNode.Attributes("code").Value = "200" Then
          MsgBox(XNode.InnerText)
        End If
      Next
    End Using
  End Sub
 
  Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    Using myReader As New StreamReader(Application.StartupPath & "\XMLFile1.xml")
      Dim MyNode = (From myElement As XElement In XDocument.Parse(myReader.ReadToEnd)...<domain> Where myElement.@code = "200" Select myElement.Value).FirstOrDefault
      MsgBox(MyNode)
    End Using
  End Sub
End Class

(Ignore my reading of your data into the project)

Hope that helps.

Cheers,

Ian
 
Inner text is returned by Value property: my_domain.Value
 
Thanks so much for your replies Ian and John! As John had said, I was able to get it using the Value property..Here is my code:
VB.NET:
my_domain.Value

Thanks again guys!!
 
Back
Top