Get value of single node yields “… value of Nothin

2019-09-01 14:12发布

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?

1条回答
成全新的幸福
2楼-- · 2019-09-01 14:38

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
查看更多
登录 后发表回答