0

I've got an XmlNode object rowNode, and when I call rowNode.OuterXml I get this result:

<Row Nr="1">
  <Område FormulaR1C1="" /> 
  <Position FormulaR1C1="" /> 
  <Lev FormulaR1C1="" /> 
  <Option FormulaR1C1="" /> 
</Row>

I'm trying to get the value of Område with the following code:

rowNode.SelectSingleNode("/Row/Område").InnerText

and I get Referenced object has a value of 'Nothing'. That's okay, I guess, because it has no value. But then I do it with another turn of the rowNode object where the XML is:

<Row Nr="2">
  <Område FormulaR1C1="1">1</Område> 
  <Position FormulaR1C1="1">1</Position> 
  <Lev FormulaR1C1="NM">NM</Lev> 
  <Option FormulaR1C1="" /> 
</Row>

And I still get Referenced object has a value of 'Nothing'. I also tried with some of the other elements - Lev and Position but I get the same "Nothing" result. What am I doing wrong?

Syspect
  • 921
  • 7
  • 22
  • 50
  • What about that `å` sign? Can you get the values of the other nodes, like `Position`? – Hexaholic May 21 '15 at 10:23
  • @Hexaholic , nope, no success. Same "nothing" result. – Syspect May 21 '15 at 10:26
  • Then I'm out. Not a VB expert, it was just a guess. – Hexaholic May 21 '15 at 10:30
  • I can't reproduce the problem. `rowNode.SelectSingleNode("/Row/Område").InnerText` return `1` given the 2nd XML. Check if your XML document has default namespace (`xmlns="...."`) – har07 May 21 '15 at 10:31
  • 1
    Try this xpath : `.//*[local-name()='Område']`, if that one works then I almost sure the problem was due to default namespace – har07 May 21 '15 at 10:33
  • @har07 , you last suggestion works. You can post it as answer, so I can accept it. :) And I also checked for namespace setup. There's a place in the code that sets up a namespace, but it's `""`, so... nothing. :D – Syspect May 21 '15 at 10:43
  • @Syspect done converting my comment to answer :) – har07 May 21 '15 at 10:54

1 Answers1

1

The problem was due to existence of default namespace. One possible way to access elements in namespace is by using XmlNamespaceManager. You need to register mapping of prefix to namespace uri to the namespace manager, and then use the registered prefix properly in the xpath :

Dim doc As New XmlDocument()
.....
Dim nsManager As New XmlNamespaceManager(doc.NameTable)
nsManager.AddNamespace("d", "your-namespace-uri-here")
Dim result = rowNode.SelectSingleNode("/d:Row/d:Område", nsManager).InnerText

Or if you don't need to consider namespaces in selecting the elements, you can just ignore it by using xpath local-name() function :

Dim result = rowNode.SelectSingleNode("/*[local-name()='Row']/*[local-name()='Område']").InnerText
har07
  • 88,338
  • 12
  • 84
  • 137