Parse a xml file in Visual basic - vb.net

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

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.

adding multiple text files to gridview (devexpress) in vb.net

I have a folder with multiple text files in it, each text files has about 14 lines of text.
I would like to add all text files in that folder to a gridcontrol/gridview in vb.net.
My current code only adds 1 text file instead of adding all. any help would be greatly appreciated.
Dim path As String = "C:\Plan\"
For Each i As String In System.IO.Directory.GetFiles(path)
Dim a, b, c As String
a = System.IO.Path.GetFileNameWithoutExtension(i)
b = System.IO.Path.GetFileName(i)
c = System.IO.Path.GetFullPath(i)
Dim LINE_pair As String = IO.File.ReadLines(i).ElementAtOrDefault(0)
Dim LINE1_details As String = IO.File.ReadLines(i).ElementAtOrDefault(1)
Dim LINE2_outlookcombo As String = IO.File.ReadLines(i).ElementAtOrDefault(2)
Dim LINE3_rsicombo As String = IO.File.ReadLines(i).ElementAtOrDefault(3)
Dim LINE4_macdcombo As String = IO.File.ReadLines(i).ElementAtOrDefault(4)
Dim LINE4_ratio As String = IO.File.ReadLines(i).ElementAtOrDefault(5)
Dim LINE5_pattern As String = IO.File.ReadLines(i).ElementAtOrDefault(6)
Dim LINE6_none As String = IO.File.ReadLines(i).ElementAtOrDefault(7)
Dim LINE7_timeframecomvo As String = IO.File.ReadLines(i).ElementAtOrDefault(8)
Dim LINE7_date As String = IO.File.ReadLines(i).ElementAtOrDefault(9)
Dim LINE8_trade As String = IO.File.ReadLines(i).ElementAtOrDefault(10)
Dim LINE9_currentprice As String = IO.File.ReadLines(i).ElementAtOrDefault(11)
Dim LINE10_tp As String = IO.File.ReadLines(i).ElementAtOrDefault(12)
Dim LINE11_sl As String = IO.File.ReadLines(i).ElementAtOrDefault(13)
Dim NewItem As New ListViewItem(a)
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(13) {New DataColumn("Pair"), New DataColumn("Outlook"), New DataColumn("RSI"), New DataColumn("MACD"), New DataColumn("Pattern"), New DataColumn("Misc"), New DataColumn("Rato"), New DataColumn("Time Frame"), New DataColumn("Date"), New DataColumn("File name"), New DataColumn("Trade Status"), New DataColumn("CP"), New DataColumn("TP"), New DataColumn("SL")})
dt.Rows.Add(New String() {LINE_pair, LINE2_outlookcombo, LINE3_rsicombo, LINE4_macdcombo, LINE5_pattern, LINE6_none, LINE4_ratio, LINE7_timeframecomvo, LINE7_date, a, LINE8_trade, LINE9_currentprice, LINE10_tp, LINE11_sl})
GridControl1.DataSource = dt
It is not necessary to declare the DataColumn array explicitly. It is created internally from the items in the braces.
You are throwing away your NewItem on each iteration. Why not add them to a list and add them all at once to a ListView.
You are reading the file over and over as you assign the LINE_ data. Read it once and use the resulting lines array.
You never use b and c in this code so I deleted them
I tested in with a .net DataGridView. The file io methods and the DataTable are the same.
Private Sub OPCode()
Dim path As String = "C:\Plan\"
Dim dt As New DataTable()
Dim lstListViewItems As New List(Of ListViewItem)
dt.Columns.AddRange({New DataColumn("Pair"), New DataColumn("Outlook"), New DataColumn("RSI"), New DataColumn("MACD"), New DataColumn("Pattern"), New DataColumn("Misc"), New DataColumn("Rato"), New DataColumn("Time Frame"), New DataColumn("Date"), New DataColumn("File name"), New DataColumn("Trade Status"), New DataColumn("CP"), New DataColumn("TP"), New DataColumn("SL")})
For Each i As String In System.IO.Directory.GetFiles(path)
Dim a = System.IO.Path.GetFileNameWithoutExtension(i)
Dim lines = File.ReadLines(i)
Dim LINE_pair As String = lines.ElementAtOrDefault(0)
Dim LINE1_details As String = lines.ElementAtOrDefault(1)
Dim LINE2_outlookcombo As String = lines.ElementAtOrDefault(2)
Dim LINE3_rsicombo As String = lines.ElementAtOrDefault(3)
Dim LINE4_macdcombo As String = lines.ElementAtOrDefault(4)
Dim LINE4_ratio As String = lines.ElementAtOrDefault(5)
Dim LINE5_pattern As String = lines.ElementAtOrDefault(6)
Dim LINE6_none As String = lines.ElementAtOrDefault(7)
Dim LINE7_timeframecomvo As String = lines.ElementAtOrDefault(8)
Dim LINE7_date As String = lines.ElementAtOrDefault(9)
Dim LINE8_trade As String = lines.ElementAtOrDefault(10)
Dim LINE9_currentprice As String = lines.ElementAtOrDefault(11)
Dim LINE10_tp As String = lines.ElementAtOrDefault(12)
Dim LINE11_sl As String = lines.ElementAtOrDefault(13)
dt.Rows.Add({LINE_pair, LINE2_outlookcombo, LINE3_rsicombo, LINE4_macdcombo, LINE5_pattern, LINE6_none, LINE4_ratio, LINE7_timeframecomvo, LINE7_date, a, LINE8_trade, LINE9_currentprice, LINE10_tp, LINE11_sl})
Dim NewItem As New ListViewItem(a)
lstListViewItems.Add(NewItem)
Next
ListView1.Items.AddRange(lstListViewItems.ToArray)
DataGridView1.DataSource = dt
End Sub

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)

How to export dataset to xml with columns caption

I need to export dataset to xml file. For this i try next sample code:
Dim dt As DataTable = New DataTable()
dt.TableName ="Test"
Dim dc As DataColumn = New DataColumn("Name", GetType(String))
dc.Caption = "ColumnCaption1"
dt.Columns.Add(dc)
Dim nr As DataRow = dt.NewRow()
nr("Name") = "TestRow"
dt.Rows.Add(nr)
Dim Xml As System.Xml.XmlDocument = New System.Xml.XmlDocument()
Dim RootNode As System.Xml.XmlNode = Xml.CreateElement("Export")
Xml.AppendChild(RootNode)
Dim DocsNode As System.Xml.XmlNode = Xml.CreateElement("Documents")
RootNode.AppendChild(DocsNode)
Dim DocDataSet As DataSet = New DataSet("Doc1")
DocDataSet.Tables.Add(dt)
DocDataSet.EnforceConstraints = False
Dim XmlDoc As System.Xml.XmlDataDocument = New System.Xml.XmlDataDocument(DocDataSet)
Dim DocElement As System.Xml.XmlNode = Xml.ImportNode(XmlDoc.DocumentElement, True)
'DocElement.
DocsNode.AppendChild(DocElement)
Dim Settings As System.Xml.XmlWriterSettings = New System.Xml.XmlWriterSettings()
Settings.Encoding = System.Text.Encoding.UTF8
Settings.Indent = True
Settings.IndentChars = Chr(9)
Settings.CloseOutput = True
Settings.OmitXmlDeclaration = true
Dim DirectoryName as string = "C:\Temp"
Dim FileName As String = DirectoryName & "\myExport"
Dim OutStream As System.IO.FileStream = System.IO.File.Create(FileName)
Dim Writer As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(OutStream, Settings)
Xml.WriteTo(Writer)
Writer.Close()
It works and the result of export is:
<Export>
<Documents>
<Doc1>
<Test>
<Name>TestRow</Name>
</Test>
</Doc1>
</Documents>
</Export>
But I want that column caption (ColumnCaption1) also will in this xml. How can i do this?

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