Comparing text to XML value - vb.net

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

Related

VB.NET Get text in between multiple Quotations

i need some help.
i need to get there text file value on Quot ("") on multi textbox1, textbox2, textbox3. but can only get on value (first value on textbox1)
now a time i just get one value (firt value on Quot)
text file (2.txt):
C:\contexture\img2itp.exe "\mynetwork\1.png" "\mynetwork\2.png" "148"
code vb:
Using sr As New StreamReader("C:\test\2.txt")
Dim line As String
' Read the stream to a string and write the string to the console.
line = sr.ReadToEnd()
Dim s As String = line
Dim i As Integer = s.IndexOf("""")
Dim f As String = s.Substring(i + 1, s.IndexOf("""", i + 1) - i - 1)
TextBox1.Text = f
thanks for a help :)
Regex Match
What Is Regex :
A regular expression is a pattern that the regular expression engine attempts to match in input text. A pattern consists of one or more character literals, operators, or constructs.
Source: https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx
Here we could consider two Regex Expressions to solve this problem a simple version and a more complex creating capture groups.
Simple one :
"(.*?)"
Here is the explanation: https://regex101.com/r/mzSmH5/1
Complex One :
(["'])(?:(?=(\\?))\2.)*?\1"(.*?)"
Here is an explanation: https://regex101.com/r/7ZMVsB/1
VB.NET Implementation
This would be a job for a Regex.Matches which would work like this:
Dim value As String = IO.File.ReadAllText("C:\test\2.txt")
Dim matches As MatchCollection = Regex.Matches(value, """(.*?)""")
' Loop over matches.
For Each m As Match In matches
' Loop over captures.
For Each c As Capture In m.Captures
' Display.
Console.WriteLine("Index={0}, Value={1}", c.Index, c.Value)
Next
Next

XML elements source contains spaces

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

String.replace adding extra characters

I am trying to replace some words in mails in Outlook. Here is my code for it
Dim input As String = mail.HTMLBody
Dim pattern As String = "QWQ[a-z][a-z][0-9][0-9][0-9][0-9][0-9]"
Dim replacement As String
Dim rgx As New Regex(pattern)
Dim match As Match = Regex.Match(input, pattern)
While (match.Success)
replacement = "A" + match.Value + "A"
input = input.Replace(match.value, replacement)
match = match.NextMatch()
End While
mail.HTMLBody = input
For this input
QWQrt12345
QWQrt1234533
wwQWQrt12345
QWQrt1234534
qwwQWQrt12345
I expect output as
AQWQrt12345A
AQWQrt12345A33
wwAQWQrt12345A
AQWQrt12345A34
qwwAQWQrt12345A
But the output I am getting is
AAAAAQWQrt12345AAAAA
AAAAAQWQrt12345AAAAA33
wwAAAAAQWQrt12345AAAAA
AAAAAQWQrt12345AAAAA34
qwwAAAAAQWQrt12345AAAAA
What can be the issue?
The description of String.Replace states,
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string.
The important takeaway there is, "all occurrences ... are replaced." Since your replacement string is also a match for your regular expression pattern, it will be replaced (thus adding another set of 'A') upon every iteration.
Try a test case using something like this, instead:
replacement = match.Value.Replace("Q", "A")
The details here don't matter (you can change whatever you want), the point is that you change something so that your strings aren't matched repeatedly.
simply put your adding 'A' + match + 'A' evertytime you match .
Resulting in the AAAAA before and after your input. I've been voted down?
ok I explain your first match input result is exactly what you have inputted(all characters could be matched), you then add "A" both sides and want to replace your replaced value with the original value.
Here's the c# code to get expected value :
var input = "QWQrt1234533"; //your second line example
const string pattern = "QWQ[a-z][a-z][0-9][0-9][0-9][0-9][0-9]";
var rgx = new Regex(pattern);
Match match = Regex.Match(input, pattern);
while (match.Success)
{
var replacement= "A" + match.Value + "A";
input = input.Replace(match.Value, replacement);
match = match.NextMatch();
}
Console.Write(input);
resulting in your exected : "AQWQrt12345A33"
not getting your results even with the posted VB code (you did not edit the original after my first response?)

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.

vb2008 match text between html tags

hello i'm using Visual Basic 2008 Express Edition
how is it possible to match text between tags?
for example i have a string : <data>Text</data>more text..., how i can get the Text which is inside <data></data> ( .Replace won't help).
thanks
My solution :
Public Function parseText(ByVal str As String, ByVal tag As String) As String
Dim match As Match = Regex.Match(str, "<" & tag & "\b[^>]*>(.*?)</" & tag & ">")
If match.Groups.Count = 2 Then
Return match.Groups(1).Value
Else
Return "0"
End If
End Function
I use this because in my case the tags will be always without id, class, width, href, src, style .... just tag name (ex:<data><str><text>...)
You can use RegularExpressions.
Dim s As String = "<data>Hello world</data>"
Dim match As Match = Regex.Match(s, "<data\b[^>]*>(.*?)</data>")
Dim text As String
If match.Groups.Count = 2 Then
text = match.Groups(1).Value
End If
Use the HTML Agility Pack to parse the HTML string and then query the resulting object for the values you want.
The source download comes with many example projects.
This may help you
Dim findtext2 As String = "(?<=<data>)(.*?)(?=</data>)"
Dim myregex2 As String = TextBox1.Text 'Your HTML code
Dim doregex2 As MatchCollection = Regex.Matches(myregex2, findtext2)
Dim matches2 As String = ""
For Each match2 As Match In doregex2
matches2 = matches2 + match2.ToString + Environment.NewLine
Next
MsgBox(matches2) 'Results
Don't forget Imports System.Text.RegularExpressions.
Above code is getting all information between 2 strings, in this case - <data> and </data>. You can use whatever you want (it doesn't need to be tag, not even html).