Search code examples
xmlvb.netxmldocument

How to select particular node from XML


I have this XML:

<?xml version="1.0"?>
    <Document xmlns="urn:somethinghere">
        <fapx.001.02>
            <Sts>
                <StsVal>ACCEPTED</StsVal>
            </Sts>
        </fapx.001.02>
    </Document>

I want to select value of "StsVal" and for that I wrote this code but getting error:

Code

Dim doc As XmlDocument = New XmlDocument()
doc.Load("myfile.xml")
Dim response As String = doc.SelectSingleNode("Document/fapx.001.02/Sts/StsVal").InnerText

Error

Object reference not set to an instance of an object.

EDIT

I know I am getting this error due to Nulll value probably because the path I have given in SelectSingleNode function is not correct. That's why I want to know how to give correct path based on given XML.


Solution

  • That's because your XML has default namespace : xmlns="urn:somethinghere". This topic (XPath query against XML with default namespace) has been asked so many times previously in various forms here in SO. Here are some from my answer history :

    1. Parse XML with succint syntax
    2. Use XPath with XML namespace
    3. Get value of single node yields "... value of Nothing"

    And this is one possible way to query element in namespace using XPath and XmlDocument :

    Dim nsManager As New XmlNamespaceManager(New NameTable())
    nsManager.AddNamespace("d", "urn:somethinghere")
    
    Dim doc As XmlDocument = New XmlDocument()
    doc.Load("myfile.xml")
    Dim response As String = doc.SelectSingleNode("d:Document/d:fapx.001.02/d:Sts/d:StsVal", nsManager).InnerText