vb net: Get string from xml, how to get three values? - vb.net

I got the genre value "Drama" but it's only one to get, How can I get three genre values like "Drama", "Comedy", and "Thriller" ??
<details>
<id>734357</id>
<title>vb best</title>
<year>2012-07-27</year>
<genre>Drama</genre>
<genre>Comedy</genre>
<genre>Thriller</genre
<studio></studio>
</details>
Dim doc As New XmlDocument()
Dim nodes As XmlNodeList
doc.Load(FILE_NAME)
nodes = doc.SelectNodes("/details")
Dim node As XmlNode
For Each node In nodes
Dim nodeid As XmlNode = node.SelectSingleNode("id")
If nodeid IsNot Nothing Then
MsgBox(node.SelectSingleNode("id").InnerText)
End If
Dim nodeimdb_id As XmlNode = node.SelectSingleNode("title")
If nodeimdb_id IsNot Nothing Then
MsgBox(node.SelectSingleNode("title").InnerText)
End If
Dim nodegenre As XmlNode = node.SelectSingleNode("genre")
If nodegenre IsNot Nothing Then
MsgBox(node.SelectSingleNode("genre").InnerText)
End If
Next

Dim doc As New XmlDocument()
Dim nodes As XmlNodeList
doc.Load(FILE_NAME)
nodes = doc.SelectNodes("/details")
Dim node As XmlNode
For Each node In nodes
Dim nodeid As XmlNode = node.SelectSingleNode("id")
If nodeid IsNot Nothing Then
MsgBox(nodeid.InnerText)
End If
Dim nodeimdb_id As XmlNode = node.SelectSingleNode("title")
If nodeimdb_id IsNot Nothing Then
MsgBox(nodeimdb_id.InnerText)
End If
Dim genreNodes As XmlNodeList = node.SelectNodes("genre")
For each genreNode in genreNodes
MsgBox(genreNode.InnerText)
Next
Next
would be one way.
Note, seeing as you'd already got the node, no need to get it again.

Use .SelectNodes instead of .SelectSingleNode

Related

Receive object reference error when iterate the xdocument to retrieve xml element value

Dim lstrReadXml As String = String.Empty
mobjComFun.ReadTextFile(System.Windows.Forms.Application.StartupPath & "\GoFirstBookingXML\GetBookRes.xml", lstrReadXml)
Dim lobjXdoc As XDocument = XDocument.Parse(lstrReadXml)
Dim lobjNs As New XmlNamespaceManager(lobjXdoc.CreateReader.NameTable)
lobjNs.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/")
lobjNs.AddNamespace("sc", "http://schemas.navitaire.com/WebServices/ServiceContracts/BookingService")
lobjNs.AddNamespace("dc", "http://schemas.navitaire.com/WebServices/DataContracts/Booking")
lobjNs.AddNamespace("a", "http://schemas.navitaire.com/WebServices/DataContracts/Common")
Dim lstrErrorMsg = String.Empty, lstrQueryStr As String = String.Empty
Dim lstrPaxNames As New StringBuilder
'Dim lstrFirstName As String = mobjComFun.GetElementValue(lobjXdoc, "/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger/dc:Names", lobjNs, lstrErrorMsg)
For Each lobXnode In lobjXdoc.XPathSelectElements("/s:Envelope/s:Body/sc:GetBookingResponse/dc:Booking/dc:Passengers/dc:Passenger", lobjNs)
If Not lobXnode Is Nothing Then
Dim lobjIEnum As IEnumerable(Of XElement) = From Nam In lobXnode.Elements(lobjNs. & "Names")
Select Nam
Dim lstrLN As String = lobXnode.Document.Element("LastName").Value
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names", lobjNs).Value)
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:LastName", lobjNs).Value & "/")
lstrPaxNames.Append(lobXnode.XPathSelectElement("/dc:Names/dc:BookingName/dc:FirstName", lobjNs).Value & " Y58TWL ")
End If
Next
When trying to foreach iterate the XDocument, I receive the object reference error when trying to get the element value inside the iteration.

Split Field in a Linq Query

Below is the content of a field name OULocationPath. I need to parse out the OU=location but only the "location". Not the "OU=".
CN=my name,OU=department,OU=location,OU=general area,DC=company,DC=org
Below is the query that I use to populate a grid. I haven't added the field above as of yet.
Public Function GetLocationList() As List(Of Contact)
GetLocationList = mContacts.FindAll(Function(x) x.Company.Contains("CompanyName") = True And x.WorkEmail = Nothing And x.WorkPhone <> "")
End Function
Thank you!
#Andrew Morton and #NetMage,
I was able to get the parse working using the code below:
Public Function GetLocationList() As List(Of Contact)
GetLocationList = Nothing
Dim Answerset = mContacts.FindAll(Function(x) x.Company.Contains("CompanyName") = True AndAlso x.WorkEmail = Nothing AndAlso x.WorkPhone IsNot Nothing)
Dim _GridLocations As New List(Of Contact)
Dim _GridLocation As Contact
_GridLocations.Clear()
For Each l In Answerset
_GridLocation = New Contact
With _GridLocation
.FullName = l.FullName
.WorkPhone = l.WorkPhone
.Extension = l.Extension
Dim s As String = l.OULocationPath
Dim sp As String() = s.Split(New [Char]() {","c, "="c})
Dim first6 As String() = sp.ToList().GetRange(0, 6).ToArray()
.OULocationPath= first6(5)
End With
_GridLocations.Add(_GridLocation)
Next
GetLocationList = _GridLocations
End Function

Issue setting DocumentElement

I'm trying to set documentelement to what I want to be the root element. When i try to do so I get the following error
Property 'DocumentElement' is readonly. I suppose that makes sense. I'm currently trying to convert msxml to system.xml.
Public Function GetXmlAllHierarchyObjects(Optional ByVal blnHideDisabled As Boolean = False) As XmlDocument
Dim recHierarchy As Recordset
Dim strSql As String = ""
Dim xmlDoc As XmlDocument = New XmlDocument()
Dim xmlRoot As XmlElement
Dim xmlParent As XmlNode
Dim intHeight As Integer
Dim xmlHierarchy As XmlElement
xmlRoot = xmlDoc.CreateElement("Hierarchy")
xmlDoc.DocumentElement = xmlRoot ' Error occurs here
recHierarchy = GetAllHierarchyObjects(blnHideDisabled, True)
Do While Not recHierarchy.EOF
xmlParent = xmlDoc.selectSingleNode("//Object[#ID='" & CStrSafe(recHierarchy("ParentID")) & "']")
If xmlParent Is Nothing Then
xmlParent = xmlRoot
intHeight = 0
Else
intHeight = CIntSafe(xmlParent.SelectSingleNode("Height").InnerText) + 1
End If
xmlHierarchy = xmlDoc.createElement("Object")
xmlParent.appendChild(xmlHierarchy)
xmlHierarchy.SetAttribute("ID", recHierarchy("ObjectID").ToString())
xmlHierarchy.appendChild(xmlDoc.createElement("Height"))
xmlHierarchy.LastChild.InnerText = CStrSafe(intHeight)
xmlHierarchy.appendChild(xmlDoc.createElement("ParentID"))
xmlHierarchy.LastChild.InnerText = CStrSafe(recHierarchy("ParentID"))
xmlHierarchy.appendChild(xmlDoc.createElement("Name"))
xmlHierarchy.LastChild.InnerText = CStrSafe(recHierarchy("Name"))
recHierarchy.MoveNext()
Loop
CloseRecordset(recHierarchy)
GetXmlAllHierarchyObjects = xmlDoc
End Function
The document element isn't really the root node. It's a level above the root. So you add your root node as a child of this.
Dim xmlDoc As XmlDocument = New XmlDocument()
Dim xmlRoot As XmlElement = xmlDoc.CreateElement("Hierarchy")
xmlDoc.AppendChild(xmlRoot)
MsgBox(xmlDoc.OuterXml)

Parse a xml file in Visual basic

which is the best way to parse this xml ???
<?xml version="1.0" encoding="UTF-8"?>
<DOCWARE Version="1.1">
<Order Count="2">
<Pos0>
<M_TEXTNR>sAuspuffendrohr</M_TEXTNR>
<VM_BESTNR>s02010000373</VM_BESTNR>
<P_PREIS>s715.80</P_PREIS>
</Pos0>
<Pos1>
<M_TEXTNR>sMutter</M_TEXTNR>
<VM_BESTNR>s02010000373</VM_BESTNR>
<P_PREIS>s0.70</P_PREIS>
</Pos1>
</Order>
<TotalSum>s</TotalSum>
</DOCWARE>
I Try to do so, but is not working then i = 1
Dim xmldoc As New XmlDataDocument()
Dim xmlnode As XmlNodeList
Dim fs As New FileStream(myFileName, FileMode.Open, FileAccess.Read)
xmldoc.Load(fs)
For i As Integer = 0 To 1
xmlnode = xmldoc.GetElementsByTagName("Pos" & i)
dim val as string = xmlnode(i).ChildNodes.Item(0).InnerText.Trim()
MsgBox(val)
Next
thanks in advance
To read a tag with a changed name you can to do using xmlReader and find if you document.Name contains this prefix "Pos", try to use this code:
Dim document As XmlReader = New XmlTextReader(fileName)
While (document.Read())
Dim type = document.NodeType
If (type = XmlNodeType.Element) Then
If (document.Name.Contains("Pos")) Then
Dim test As String = document.ReadInnerXml.ToString()
Dim doc As New XmlDocument()
doc.LoadXml("<Pos>" & test & "</Pos>")
Dim root As XmlNode = doc.FirstChild
If root.HasChildNodes Then
dim _value = root.ChildNodes.Item(0).InnerText.Trim()
End If
End If
End If
End While

How to extract Atom/RSS

Given a URL, if it has any RSS nodes, then I am adding to the database.
e.g.:
For this URL, rssDoc.SelectNodes("rss/channel/item").Count is greater than zero.
But for the atom url, rssDoc.SelectNodes("rss/channel/item").count is equal to zero.
How can I check if the Atom/RSS URL has any nodes or not? I have tried for rssDoc.SelectNodes("feed/entry").Count, but is giving me zero count.
Public Shared Function HasRssItems(ByVal url as string) As Boolean
Dim myRequest As WebRequest
Dim myResponse As WebResponse
Try
myRequest = System.Net.WebRequest.Create(url)
myRequest.Timeout = 5000
myResponse = myRequest.GetResponse()
Dim rssStream As Stream = myResponse.GetResponseStream()
Dim rssDoc As New XmlDocument()
rssDoc.Load(rssStream)
Return rssDoc.SelectNodes("rss/channel/item").Count > 0
Catch ex As Exception
Return False
Finally
myResponse.Close()
End Try
End Function
Your main problem here is that the XML "node path" on this line:
Return rssDoc.SelectNodes("rss/channel/item").Count > 0
is only valid for RSS feeds, not ATOM feeds.
One way I've got over this in the past is to use a simple function to convert an ATOM feed into an RSS feed. Of course, you could go the other way, or not convert at all, however, converting to a single format enables you to write one "generic" chunk of code that will pull out the various elements of a feed's items that you may be interested in (i.e. date, title etc.)
There is an ATOM to RSS Converter article on Code Project that provides such a conversion, however, that is in C#. I have previously manually converted this to VB.NET myself, so here's the VB.NET version:
Private Function AtomToRssConverter(ByVal atomDoc As XmlDocument) As XmlDocument
Dim xmlDoc As XmlDocument = atomDoc
Dim xmlNode As XmlNode = Nothing
Dim mgr As New XmlNamespaceManager(xmlDoc.NameTable)
mgr.AddNamespace("atom", "http://purl.org/atom/ns#")
Const rssVersion As String = "2.0"
Const rssLanguage As String = "en-US"
Dim rssGenerator As String = "RDFFeedConverter"
Dim memoryStream As New MemoryStream()
Dim xmlWriter As New XmlTextWriter(memoryStream, Nothing)
xmlWriter.Formatting = Formatting.Indented
Dim feedTitle As String = ""
Dim feedLink As String = ""
Dim rssDescription As String = ""
xmlNode = xmlDoc.SelectSingleNode("//atom:title", mgr)
If xmlNode Is Nothing Then
This looks like an ATOM v1.0 format, rather than ATOM v0.3.
mgr.RemoveNamespace("atom", "http://purl.org/atom/ns#")
mgr.AddNamespace("atom", "http://www.w3.org/2005/Atom")
End If
xmlNode = xmlDoc.SelectSingleNode("//atom:title", mgr)
If Not xmlNode Is Nothing Then
feedTitle = xmlNode.InnerText
End If
xmlNode = xmlDoc.SelectNodes("//atom:link/#href", mgr)(2)
If Not xmlNode Is Nothing Then
feedLink = xmlNode.InnerText
End If
xmlNode = xmlDoc.SelectSingleNode("//atom:tagline", mgr)
If Not xmlNode Is Nothing Then
rssDescription = xmlNode.InnerText
End If
xmlNode = xmlDoc.SelectSingleNode("//atom:subtitle", mgr)
If Not xmlNode Is Nothing Then
rssDescription = xmlNode.InnerText
End If
xmlWriter.WriteStartElement("rss")
xmlWriter.WriteAttributeString("version", rssVersion)
xmlWriter.WriteStartElement("channel")
xmlWriter.WriteElementString("title", feedTitle)
xmlWriter.WriteElementString("link", feedLink)
xmlWriter.WriteElementString("description", rssDescription)
xmlWriter.WriteElementString("language", rssLanguage)
xmlWriter.WriteElementString("generator", rssGenerator)
Dim items As XmlNodeList = xmlDoc.SelectNodes("//atom:entry", mgr)
If items Is Nothing Then
Throw New FormatException("Atom feed is not in expected format. ")
Else
Dim title As String = [String].Empty
Dim link As String = [String].Empty
Dim description As String = [String].Empty
Dim author As String = [String].Empty
Dim pubDate As String = [String].Empty
For i As Integer = 0 To items.Count - 1
Dim nodTitle As XmlNode = items(i)
xmlNode = nodTitle.SelectSingleNode("atom:title", mgr)
If Not xmlNode Is Nothing Then
title = xmlNode.InnerText
End If
Try
link = items(i).SelectSingleNode("atom:link[#rel= alternate ]", mgr).Attributes("href").InnerText
Catch ex As Exception
link = items(i).SelectSingleNode("atom:link", mgr).Attributes("href").InnerText
End Try
xmlNode = items(i).SelectSingleNode("atom:content", mgr)
If Not xmlNode Is Nothing Then
description = xmlNode.InnerText
End If
xmlNode = items(i).SelectSingleNode("//atom:name", mgr)
If Not xmlNode Is Nothing Then
author = xmlNode.InnerText
End If
xmlNode = items(i).SelectSingleNode("atom:issued", mgr)
If Not xmlNode Is Nothing Then
pubDate = xmlNode.InnerText
End If
xmlNode = items(i).SelectSingleNode("atom:updated", mgr)
If Not xmlNode Is Nothing Then
pubDate = xmlNode.InnerText
End If
xmlWriter.WriteStartElement("item")
xmlWriter.WriteElementString("title", title)
xmlWriter.WriteElementString("link", link)
If pubDate.Length < 1 Then
pubDate = Date.MinValue.ToString()
End If
xmlWriter.WriteElementString("pubDate", Convert.ToDateTime(pubDate).ToUniversalTime().ToString("ddd, dd MMM yyyy HH:mm:ss G\MT"))
xmlWriter.WriteElementString("author", author)
xmlWriter.WriteElementString("description", description)
xmlWriter.WriteEndElement()
Next
xmlWriter.WriteEndElement()
xmlWriter.Flush()
xmlWriter.Close()
End If
Dim retDoc As New XmlDocument()
Dim outStr As String = Encoding.UTF8.GetString(memoryStream.ToArray())
retDoc.LoadXml(outStr)
Return retDoc
End Function
Usage is fairly straight forward. Simply load in your ATOM feed into an XmlDocument object and pass it to this function, and you'll get an XmlDocument object back, in RSS format!
If you're interested, I've put an entire RSSReader class up on pastebin.com