Reputation: 1112
I'm storing multiple values in a string in a database. I need to split the string up when I retrieve it to assign it to different unique variables. I'm doing this in VB, and vb is still a bit new to me.
Dim scourceString = "<Var1>Person Name</Var1><Var2>11/11/13</Var2><Var3>Somthing else</Var3>"
<var#>
i'm dealing with.Any suggestions on how to do this welcome.
Edit:
I've tried this:
Dim sx As String = "<tag1>test</tag1> <tag2>testa2</tag2> <tag3>test3</tag3>"
Dim sb As String = sx.Split(New [String]() {"<tag2>"}, StringSplitOptions.RemoveEmptyEntries)(1).Split(New [String]() {"</tag2>"}, StringSplitOptions.RemoveEmptyEntries)(0)
I can get the values but it's dirty.
Upvotes: 1
Views: 664
Reputation: 9414
Try this
Dim s As String = "<Var1>Person Name</Var1><Var2>11/11/13</Var2><Var3>Somthing else</Var3>"
s = "<root>" & s & "</root>"
Dim doc As XDocument = XDocument.Parse(s)
Dim arr As XElement() = doc.Root.Elements().ToArray()
For Each item As XElement In arr
Response.Write(Convert.ToString(item) & "<br>")
Next
Upvotes: 2
Reputation: 43743
If you know that the data is always going to be formatted with beginning and ending XML tags, like that, all you need to do to make it a well-formed XML document is to add a root element, like this:
Public Function ParseData(data As String) As MyData
Dim doc As XDocument = XDocument.Parse("<Root>" + data + "</Root>")
Dim values As New MyData()
values.Var1 = doc.<Root>.<Var1>.Value
values.Var2 = doc.<Root>.<Var2>.Value
values.Var3 = doc.<Root>.<Var3>.Value
Return values
End Function
Public Class MyData
Public Property Var1 As String
Public Property Var2 As String
Public Property Var3 As String
End Class
Then you could call the method like this:
Dim scourceString As String = "<Var1>Person Name</Var1><Var2>11/11/13</Var2><Var3>Somthing else</Var3>"
Dim values As MyData = ParseData(scourceString)
Console.WriteLine(values.Var1)
Console.WriteLine(values.Var2)
Console.WriteLine(values.Var3)
Upvotes: 2
Reputation: 2562
You can not split the string with <Var#>
as you don't not what exactly the "#" value is. So what you can do is store the value with a common and unique
separator like (use "¥"
or what you want)
Dim scourceString = "Person Name¥11/11/13¥Somthing else"
Now to split the string try split method like this
Dim TestArray() As String = scourceString.Split("¥")
you have all the values in the TestArray() and you can access them by index as TestArray(0), TestArray(1) .....
Upvotes: 0