Problem querying XML string asp.net

  • Thread starter Thread starter DarthSidious
  • Start date Start date
D

DarthSidious

hello!!
i've a problem trying to query an xml string

i receive an xml string as the one below, from a web service,

<Product>
<Suc>
<Numo>333</Numo>
</Suc>
<Detop>
<Numo>0</Numo>
<Extra><Extra/>
</Detop>
</Product>

what i'm trying to do is a query on that xml string to get the value that's
in
/Product/Detop/Numo which in this case would be 0.
this is what i do:

Dim ms As System.IO.MemoryStream = New
System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(StringXML))

Dim xpdoc As New XPathDocument(ms)
Dim xpnd As XPathNodeIterator
Dim xpnav As XPathNavigator
xpnav = xpdoc.CreateNavigator()
Dim query As XPathExpression = xpnav.Compile("/Product/Detop/Numo")
xpnd = xpnav.Select(query)
sResp = xpnd.Current.Value

according to this code, i would have to get a 0, but what i really get after
querying
is a 3330.

this is like if the values in /Product/Detop/Numo and /Product/Suc/Numo were
concatenating. "333" + "0" = "3330"

what's wrong with this code?

thanks in advance!
 
DarthSidious said:
Dim ms As System.IO.MemoryStream = New
System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(StringXML))

Dim xpdoc As New XPathDocument(ms)

You don't need a MemoryStream, simply do
Dim xpdoc As New XPathDocument(new StringReader(StringXML))
Dim xpnd As XPathNodeIterator
Dim xpnav As XPathNavigator
xpnav = xpdoc.CreateNavigator()
Dim query As XPathExpression = xpnav.Compile("/Product/Detop/Numo")
xpnd = xpnav.Select(query)
sResp = xpnd.Current.Value

according to this code, i would have to get a 0, but what i really get after
querying
is a 3330.

Consider to simply use SelectSingleNode e.g.
Dim numo As XPathNavigator = xpnav.SelectSingleNode("Product/Detop/Numo")
If numo IsNot Nothing Then
sResp = numo.Value
Else
' not not found
End If

SelectSingleNode is .NET 2.0 and later.

If you are still using .NET 1.x then you need to use the Select method
and use the XPathNodeIterator but in that case you have to call
MoveNext() first on it before you can access the first value.
 
thanks!!! it worked perfect!

:-)

Martin Honnen said:
You don't need a MemoryStream, simply do
Dim xpdoc As New XPathDocument(new StringReader(StringXML))


Consider to simply use SelectSingleNode e.g.
Dim numo As XPathNavigator = xpnav.SelectSingleNode("Product/Detop/Numo")
If numo IsNot Nothing Then
sResp = numo.Value
Else
' not not found
End If

SelectSingleNode is .NET 2.0 and later.

If you are still using .NET 1.x then you need to use the Select method
and use the XPathNodeIterator but in that case you have to call
MoveNext() first on it before you can access the first value.
 
Back
Top