I have the below xml file and I need to use an xpath to get “amount” value based on “linenumber”.
<Doc>
<Documents>
<Document1>
<linenumber>800</linenumber>
<amount>100.00</amount>
<name>fee1</name>
</Document1>
<Document2>
<linenumber>801</linenumber>
<amount>200.00</amount>
<name>fee2</name>
</Document2>
<Document3>
<linenumber>802</linenumber>
<amount>300.00</amount>
<name>fee3</name>
</Document3>
<Document4>
<linenumber>803</linenumber>
<amount>400.00</amount>
<name>fee4</name>
</Document4>
</Documents>
</Doc>
I tried the xpath specified in the below function ‘GetDocumentField’ but the function call GetDocumentField(801, “amount”) did not return any value. I can’t use LINQ since it is based on .Net framework 2.0. Can anyone suggest how to write this xpath query? Thanks!
Private Function GetDocumentField(ByVal line As Integer, ByVal field As String) As String
Return GetValueFromXPath(String.Format("//linenumber[.='{0}']/parent::node()/{1}", line, field)))
End Function
Private Function GetValueFromXPath(ByVal xpath As String) As String
Dim node As XmlNode
node = InputXml.SelectSingleNode(xpath)
Return GetValueFromNode(node)
End Function
Private Function GetValueFromNode(ByVal node As XmlNode) As String
If node Is Nothing Then
Return String.Empty
End If
If node.InnerText Is Nothing Then
Return String.Empty
End If
Return node.InnerText
End Function
Use this XPath expression:
But before this, correct the presented non-well-formed XML document (you probably didn’t notice that there was a parsing exception when you loaded
InputXml). More specifically, allamountelements have no closing tag.