Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

converting an XMLDocument to an XPathDocument

Status
Not open for further replies.

Kai77

Programmer
Jun 7, 2004
77
NL
Hi,

I am tryin to navigate through an XMLDocument using XPathNavigator. PagesXML is a valid xmldocument and i am trying to assign it to xpathDoc by casting it. But I am getting a 'Specified cast is invalid' message. How can I navigate through the XML?

Dim getSurveyPagesXML As New getSurveyXML
Dim PagesXML As XmlDocument = getSurveyPagesXML.getXML(strFolder, "pages")

Dim xpathDoc As XPathDocument
Dim xmlNav As XPathNavigator
Dim xmlNI As XPathNodeIterator

Try
xpathDoc = DirectCast(PagesXML, XPathDocument)
xmlNav = xpathDoc.CreateNavigator()
xmlNI = xmlNav.Select("/list_pages/page")
While (xmlNI.MoveNext())
System.Console.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
End While
Catch ex As XPathException
System.Console.WriteLine("XMLException: " + ex.Message)
Catch ex As Exception
System.Console.WriteLine("Exception: " + ex.Message)
End Try
 
I solved by not defining PagesXML as an xmldocument, but as a string, so it can be read by the xmltextreader and assign the reader to the xpathdocument.

So now it looks like this:

Dim getSurveyPagesXML As New getSurveyXML
Dim PagesXML As String = getSurveyPagesXML.getXML(strFolder, "pages")

Dim xpathDoc As XPathDocument
Dim xmlNav As XPathNavigator
Dim xmlNI As XPathNodeIterator
Dim xmlreader As XmlTextReader = New XmlTextReader(PagesXML, XmlNodeType.Element, Nothing)

Try
xpathDoc = New XPathDocument(xmlreader, XmlSpace.Preserve)
xmlNav = xpathDoc.CreateNavigator()
xmlNI = xmlNav.Select("/list_pages/page")
While (xmlNI.MoveNext())
System.Console.WriteLine(xmlNI.Current.Name + " : " + xmlNI.Current.Value)
End While
Catch ex As XPathException
System.Console.WriteLine("XMLException: " + ex.Message)
Catch ex As Exception
System.Console.WriteLine("Exception: " + ex.Message)
End Try
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top