XML elements source contains spaces - vb.net

I'm very new in reading XML content and now i'm running into the issue that some XML elements are containing a white space and VB.net is not accepting this.
Please have a look at the line of code starting with "Today_CurrentTemp". In this line you find an element , the space and quotes are not accepted like this by the XDocument.
Please help me how to work arround this. I cannot change the XML source format.
Const URL As String = "http://xml.buienradar.nl/"
Try
Dim xml = XDocument.Load(URL)
Today_DescriptionShort = xml.<buienradarnl>.<weergegevens>.<verwachting_vandaag>.<samenvatting>.Value
Today_DescriptionLong = xml.<buienradarnl>.<weergegevens>.<verwachting_vandaag>.<tekst>.Value
Today_CurrentTemp = xml.<buienradarnl>.<weergegevens>.<actueel_weer>.<weerstations>.<weerstation id="6391">.<temperatuurGC>.Value

The element <weerstation id="6391"> does not contain whitespace in its name.
The whitespace indicates that the next literal is considered as an Xml Attribute with a specific value in double quotes (id="6391").
Here is how you get the current temp:
Today_CurrentTemp = xml.<buienradarnl>.<weergegevens>.<actueel_weer>.<weerstations>.<weerstation>.Where(Function (x) x.Attribute("id") = "6391").First().<temperatuurGC>.Value
I used a lambda expression to give me the first occurance of an element named <weerstation> with an Attribute named id and value 6391.
I assume that the id is unqiue so the .First() appraoch is correct.

That works perfectly!
Now I have a similar issue with the line
<icoonactueel zin="bewolkt" ID="p">http://xml.buienradar.nl/icons/p.gif</icoonactueel>
<temperatuur10cm>11.3</temperatuur10cm>
Where bewolkt can have different values and the ID changes as wel, based on the type of weather. The only that I would like to have out of this element is the URL.
How to handle this?
see part of the XML below as example:
<weerstation id="6391">
<stationcode>6391</stationcode>
<stationnaam regio="Venlo">Meetstation Arcen</stationnaam>
<lat>51.30</lat>
<lon>6.12</lon>
<datum>04/13/2016 11:50:00</datum>
<luchtvochtigheid>83</luchtvochtigheid>
<temperatuurGC>10.5</temperatuurGC>
<windsnelheidMS>2.12</windsnelheidMS>
<windsnelheidBF>2</windsnelheidBF>
<windrichtingGR>123.0</windrichtingGR>
<windrichting>OZO</windrichting>
<luchtdruk>-</luchtdruk>
<zichtmeters>-</zichtmeters>
<windstotenMS>3.7</windstotenMS>
<regenMMPU>-</regenMMPU>
<icoonactueel zin="bewolkt" ID="p">http://xml.buienradar.nl/icons/p.gif</icoonactueel>
<temperatuur10cm>11.3</temperatuur10cm>

Try this...
Const URL As String = "http://xml.buienradar.nl/"
Sub Main()
Dim Today_DescriptionShort
Dim Today_DescriptionLong
Dim Today_CurrentTemp
Try
Dim xsrcdoc = XDocument.Load(URL)
Today_DescriptionShort = (From xml In xsrcdoc.Descendants("verwachting_vandaag")
Select New With {.Val = xml.Element("samenvatting").Value}).FirstOrDefault
Today_DescriptionLong = (From xml In xsrcdoc.Descendants("verwachting_vandaag")
Select New With {.Val = xml.Element("tekst").Value}).FirstOrDefault
Today_CurrentTemp = (From xml In xsrcdoc.Descendants("weerstation").Where(Function(x) x.Attribute("id").Value = "6391")
Select New With {.Val = xml.Element("temperatuurGC").Value}).FirstOrDefault
Catch ex As Exception
End Try
End Sub

Related

I used these codes but return an error as an invalid string Format

I used these codes but return an error as an invalid string Format.
can you guide me?:)
Dim orderRequest As BamboraOrderRequest = New BamboraOrderRequest
orderRequest.id = objCartData.GetOrderNumberWithoutInceasing()
If Session("CardPaymentTotalPrice").ToString().Contains(",") Then
orderRequest.amount = Convert.ToInt32(Session("CardPaymentTotalPrice").ToString().Replace(",", ""))
Else
orderRequest.amount = Convert.ToInt32(Session("CardPaymentTotalPrice").ToString())
End If
orderRequest.currency = "DKK"
With the information you have provided, it is unclear where the error occurs and what values are given, but you could try editing the code as follows to see if that helps:
Dim orderRequest As BamboraOrderRequest = New BamboraOrderRequest
orderRequest.id = objCartData.GetOrderNumberWithoutInceasing()
orderRequest.amount = Convert.ToInt32(Session("CardPaymentTotalPrice").ToString().Replace(",", ""))
orderRequest.currency = "DKK"
The String.Replace method only replaces the character if it exists, eliminating the need for the If statement.
Try this and if it doesn't work please provide more details about the issue. It would also be helpful to know what value Session("CardPaymentTotalPrice") returns.

VB.NET and XmlElement() How do I get the value of the elements out of an API call?

I have a successful API call and return of data in an XmlElement however I am not able to find out how to parse out the data I need.
Dim Any = CardInqResponse.CardInqRec.Custom.Any <-- This is my xmlelement.
My return shows Length of two (two Elements).
My element names are Exp and Offset.
I am interested in the data in Offset where I can see these values returned in innerText and innerXml.
How do I get the value of either of these two to store in a string?
Load API response into XmlDocument and select a node with xpath and get innertext of selected node. below example is for an idea
Dim doc = new XmlDocument()
doc.LoadXml(yourXmlString)
txtStreet.Text = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
For more info refer https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument?redirectedfrom=MSDN&view=netcore-3.1
Moreover you can share you response then i can see how can we get your required data.
Dim offset As String
Dim Any = CardInqResponse.CardInqRec.Custom.Any
For Each node As XmlElement In Any
If node.Name = "Offset" Then
Try
offset = node.InnerText.ToString
Catch
End Try
End If
Next

VB Loading a list of variables from a text document

I'm currently trying to load a list of variables that are formatted like this:
5,
6,
3,
3,
etc, and I'm trying to output them to variables like this:
Strength = variablesList(1)
Agility = variablesList(2)
But so far, I've not been able to find a solution that seems to work for what I'm trying to do.
I'm currently working with:
Dim destination As String = Environment.GetFolderPath("C:\Roll20Output\Class" + outputClass + "2.txt")
Dim FileReader1 As New StreamReader(destination)
Dim Contents1 As String
Dim index As Integer = 0
While FileReader1.Peek <> -1
Contents1 = FileReader1.ReadLine
Dim array As New ArrayList
array.AddRange(Contents1.Split(","))
variablesList.Add(array)
End While
Strength = variablesList(1)
Agility = variablesList(2)
But so far I can't seem to get anything to output.
Would anyone be able to help?
Thanks
You are using a lot of outdated stuff in your code (reading a file with StreamReader, ArrayList instead of List<T>, etc.). I would suggest the following (untested):
' Returns an array with one string per line
Dim lines = File.ReadAllLines("C:\...\SomeFile.txt")
' Remove trailing `,` - LINQ magic
lines = (From s In lines Select s.TrimEnd(","c)).ToArray()
Dim strength = CInt(lines(0))
Dim agility = CInt(lines(1))
...
If you get rid of the useless trailing commas, you can skip the second step. If you use only commas instead of new lines, the first step becomes:
Dim lines = File.ReadAllText("C:\...\SomeFile.txt").Split(","c)

Comparing text to XML value

I am trying to have a application do the follow:
If Combobox1 text is the same as <Name1></Name1> in a .XML, then input "They Match" into a textbox.
This is the code I am trying anyways
Dim DocList As String = "C:\Users\jefhill\Desktop"
Dim Name1 As String
Dim Name2 As String
Name1 = (XElement.Load(DocList + "\parts.xml").<Name1>.Single)
Name2 = (XElement.Load(DocList + "\parts.xml").<Name2>.Single)
If ComboBox1.Text = Name1 Then
DesTextBox.Text = (XElement.Load(DocList + "\parts.xml").<Des1>.Single)
ElseIf ComboBox1.Text = Name2 Then
DesTextBox.Text = (XElement.Load(DocList + "\parts.xml").<Des2>.Single)
'ect
XML document example:
<Name1>Words</Name1>
<Name2>More Words</Name2>
EDIT: Forgot to mention the error.
Sequence contains no elements
The error
Sequence contains no elements
comes from calling .Single() when no matching elements were found, which implies that one or more of the element names you are querying for are missing from your XML document. Since the XML you provided is incomplete, I can't tell which that may be. It may be a simple typo.
There are a couple of other issues in your code. I would recommend using Option Strict On to avoid some of those issues.
You should only load the XML document once:
Dim xml As XElement = XElement.Load(DocList + "\parts.xml")
You should use .Value to get the string value for an element, since the .Single() will return an XElement:
Dim Name1 As String = xml.<Name1>.Single().Value
Dim Name2 As String = xml.<Name2>.Single().Value

Splitting string in VB.NET produces unusual results

I am using the Split function in VB.NET, and it is producing a weird result when I display the output.
I have an XML document, and I just want to loop through each <backup> tag in the document, so I am using:
Dim XMLString As String
XMLString = "<backup>INFO</backup><backup>ANOTHER INFO</backup>"
Dim SplitBackup As String()
SplitBackup = XMLString.Split("<backup>")
For Each BackupContent In SplitBackup
MsgBox(BackupContent)
Next
Now, one would expect this to output INFO in a MsgBox, I click OK and then another one would popup and show 'ANOTHER INFO', but it seems that the Split function is getting stuffed up with the '<' and '>' in it. Is there someway I can get around this by escaping it, or parsing it some other way.
Any suggestions are much appreciated!
Give XML a chance.
Dim bups As XElement = <backups><backup>INFO</backup><backup>ANOTHER INFO</backup></backups>
For Each xe As XElement In bups.Elements
Debug.WriteLine(xe.Value)
Next
One possibility to do this is to use regular expression to split the tags (and escape the problematic symbols) and then use LINQ to Objects to get the value from each tag:
Dim XMLString As String = "<backup>INFO</backup><backup>ANOTHER INFO</backup>"
Dim words = Regex.Split(XmlString, "\<backup\>").Where(function(f) not String.IsNullOrEmpty(f)).Select(function(f) f.Replace("</backup>", String.Empty)) '
for each word in words
Console.WriteLine(word)
next word
The output is:
INFO
ANOTHER INFO
What the code does:
Dim words = Regex
' split on every tag
.Split(XmlString, "\<backup\>")
' remove empty items
.Where(function(f) not String.IsNullOrEmpty(f))
' remove trailing closing tag and thus retrieve the value within
.Select(function(f) f.Replace("</backup>", String.Empty))
As already suggested you better learn how to use the build-in XML support - it is easier and safer because you do not need to pay attention to the brackets - < and > are automatically handled. A possible solution could look like this (! you need to have a valid XML structure - one unique root node!):
' !!! you need to have a valid XML element - one root node !!!
Dim XMLString As String = "<root><backup>INFO</backup><backup>ANOTHER INFO</backup></root>"
dim words = XDocument.Parse(XMLString).Root.Descendants("backup").Select(function (f) f.Value)
for each word in words
Console.WriteLine(word)
next word
The output is the same as above. How does the code work:
dim words = XDocument
' parse the specified XML structure; use Load("file.xml") to load from file
.Parse(XMLString)
' from the root node
.Root
' take all nodes matching the specified tag
' note - no need to pay attention to the < and >
.Descendants("backup")
' select the value of the XML node
.Select(function (f) f.Value)
You would need to get rid of the close element.
So you could use:
Dim XMLString As String
XMLString = "<backup>INFO</backup><backup>ANOTHER INFO</backup>"
Dim SplitBackup As String()
SplitBackup = XMLString.Split("<backup>")
For Each BackupContent In SplitBackup
Dim Something() as string
Something = BackupContent.Split("</backup">)
MsgBox(Something(0))
Next
Not the most elegant coding though.