Reading XML String

J

jimmy

Hi,

I have an XML string that has been returned using a WebRequest object
that i now need extract some data from. Some sample data is shown
below.

<?xml version="1.0" encoding="UTF-8"?>
<ISBNdb server_time="2005-02-25T23:03:41">
<BookList total_results="1" page_size="10" page_number="1"
shown_results="1">
<BookData book_id="somebook" isbn="0123456789">
<Title>Interesting Book</Title>
<TitleLong>Interesting Book: Read it or else..</TitleLong>
<AuthorsText>John Doe</AuthorsText>
<PublisherText>Acme Publishing</PublisherText>
</BookData>
</BookList>
</ISBNdb>

I now need to extract the 'Title', 'AuthorsText' and 'PublisherText'
from it. Can anyone point me in the right direction because all the
samples ive seen are for reading xml files and not a string.

Thanks

James
 
M

Martin Honnen

jimmy said:
I now need to extract the 'Title', 'AuthorsText' and 'PublisherText'
from it. Can anyone point me in the right direction because all the
samples ive seen are for reading xml files and not a string.

All XML APIs (like XmlReader or XPathDocument or XmlDocument) can read
from a file or from a string, you can simply provide a StringReader over
your string with XML.

Here is an example reading out the stuff using XPathNavigator, assuming
Xml is your string variable

Dim Doc As XPathDocument = New XPathDocument(New StringReader(Xml))
Dim Navigator As XPathNavigator = Doc.CreateNavigator()
Dim NodeIterator As XPathNodeIterator =
Navigator.Select("ISBNdb/BookList/BookData")
While NodeIterator.MoveNext()
Console.WriteLine("Book ISBN: {0}:",
NodeIterator.Current.GetAttribute("isbn", ""))
Console.WriteLine("Title: {0}",
NodeIterator.Current.SelectSingleNode("Title").Value)
Console.WriteLine("Author: {0}",
NodeIterator.Current.SelectSingleNode("AuthorsText").Value)
Console.WriteLine("Publisher: {0}",
NodeIterator.Current.SelectSingleNode("PublisherText").Value)
Console.WriteLine()
End While
 
H

Heikki Leivo

Here is an example reading out the stuff using XPathNavigator, assuming
Xml is your string variable

Altough the result is the same, I find personally xmlDocument more
straightforward way, for example

Dim document As New System.Xml.XmlDocument
document.LoadXml(xml) 'assuming that xml contains your xml document

Dim path As String = "ISBNdb/BookList/BookData[@book_id=""somebook""]"
Dim bookElement As System.Xml.XmlElement =
CType(document.SelectSingleNode(path), Xml.XmlElement)

Console.WriteLine("Book isbn: " & bookElement.GetAttribute("isbn")
Console.WriteLine("Title: " & bookElement.SelectSingleNode("Title").Value)
Console.WriteLine("Author: " &
bookElement.SelectSingleNode("AuthorsText").Value)
etc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top