Converting string to XML node in VB.NET - asp.net

I've an XML string in database column like this
<trueFalseQuestion id="585" status="correct" maxPoints="10"
maxAttempts="1"
awardedPoints="10"
usedAttempts="1"
xmlns="http://www.ispringsolutions.com/ispring/quizbuilder/quizresults">
<direction>You have NO control over how you treat customers.</direction>
<answers correctAnswerIndex="1" userAnswerIndex="1">
<answer>True</answer>
<answer>False</answer>
</answers>
</trueFalseQuestion>
But I need to do XML operations on this string like select its name, attributes values,inner text etc. How can I make this possible from this string
EDIT
Im sharing the code snippet I tried, but not working
Dim myXML As String
Dim gDt As New DataTable
gDt.Columns.Add("id")
gDt.Columns.Add("questionid")
gDt.Columns.Add("serial")
gDt.Columns.Add("direction")
Dim dr As DataRow
myXML ='<my above shared XML>'
Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml(myXML)
dr = gDt.NewRow
dr("serial") = 1
dr("id") = xmlDoc.Attributes("id").Value
dr("direction") = xmlDoc("direction").InnerText
gDt.Rows.Add(dr)
But thats not working at all as I wish

There are many ways to parse XML in .NET, such as using one of the serialization classes or the XmlReader class, but the two most popular options would be to parse it with either XElement or XmlDocument. For instance:
Dim input As String = "<trueFalseQuestion id=""585"" status=""correct"" maxPoints=""10"" maxAttempts=""1"" awardedPoints=""10"" usedAttempts=""1"" xmlns=""http://www.ispringsolutions.com/ispring/quizbuilder/quizresults""><direction>You have NO control over how you treat customers.</direction><answers correctAnswerIndex=""1"" userAnswerIndex=""1""><answer>True</answer><answer>False</answer></answers></trueFalseQuestion>"
Dim element As XElement = XElement.Parse(input)
Dim id As String = element.#id
Or:
Dim input As String = "<trueFalseQuestion id=""585"" status=""correct"" maxPoints=""10"" maxAttempts=""1"" awardedPoints=""10"" usedAttempts=""1"" xmlns=""http://www.ispringsolutions.com/ispring/quizbuilder/quizresults""><direction>You have NO control over how you treat customers.</direction><answers correctAnswerIndex=""1"" userAnswerIndex=""1""><answer>True</answer><answer>False</answer></answers></trueFalseQuestion>"
Dim doc As New XmlDocument()
doc.LoadXml(input)
Dim nsmgr As New XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("q", "http://www.ispringsolutions.com/ispring/quizbuilder/quizresults")
Dim id As String = doc.SelectSingleNode("/q:trueFalseQuestion/#id", nsmgr).InnerText
Based on your updated question, it looks like the trouble you were having is that you weren't properly specifying the namespace. If you use XElement, it's much more forgiving (i.e. loose), but when you use XPath to select nodes in an XmlDocument, you need to specify every namespace, even when it's the default namespace on the top-level element of the document.

Related

process webclients data with xquery

I retrieve the html from a cross domain web page using asp.net vb
Dim objWebClient As New WebClient()
objWebClient.UseDefaultCredentials = True
objWebClient.Headers.Add(HttpRequestHeader.UserAgent, "XPlorer")
'STEP 2: Call the DownloadedData method
Const strURL As String = "http://www.example.com"
Dim aRequestedHTML() As Byte
aRequestedHTML = objWebClient.DownloadData(strURL)
'STEP 3: Convert the Byte array into a String
Dim objUTF8 As New UTF8Encoding()
Dim strRequestedHTML As String
strRequestedHTML = objUTF8.GetString(aRequestedHTML)
Additionally I want show just a portion of it in a literal control. As an example I want to show just the table with the class "result".
How do I process this further in XML and XQuery in VB.NET? How do I declare strRequestedHTML as XML and how do I xquery in it?
thx in advance...
If your talking about a webpage (html) it would be better to parse it as HTML rather than XML.
Html Agility Pack is a good open source HTML parser for .NET
You could also use Html Agility Pack do download the web page aswell.
Something like:
Dim htmlWeb As HtmlAgilityPack.HtmlWeb = New HtmlWeb()
Dim htmlDocument As HtmlAgilityPack.HtmlDocument = htmlWeb.Load("http://www.google.com")
Dim htmlNode As HtmlAgilityPack.HtmlNode = htmlDocument.DocumentNode.SelectSingleNode("//table[#class='result']")
Response.Write(htmlNode)

System.Xml.Linq Namespace

I have been given the task of calling a web service which returns an xml data feed which I am doing like so;
For Each r As DataRow in SomeDataTable
Dim msFeed As String = string.format("http://some-feed.com?param={0}", r!SOME_VAL)
Dim x As XDocument = XDocument.Load(msFeed)
Next
This is all fine but as you can see x just gets overwritten with every iteration. What I need is create an xDocument and add each feed from my loop but I am unsure how to proceed.
Thanks
Solution
Dim xAllFeeds As XElement = New XElement("Feeds")
For Each r As DataRow in SomeDataTable
Dim msFeed As String = string.format("http://some-feed.com?param={0}", r!SOME_VAL)
Dim x As XDocument = XDocument.Load(msFeed)
xAllFeeds.Add(x.Root)
Next
Not 100% sure of the VB syntax (C# is my language of choice), but this should be the gist of what you're after.
Dim xAllFeeds As XElement = New XElement("Feeds")
For Each r As DataRow in SomeDataTable
Dim msFeed As String = string.format("http://some-feed.com?param={0}", r!SOME_VAL)
Dim xDoc As XDocument = XDocument.Load(msFeed)
xAllFeeds.Add(xDoc.Root)
Next

How to fill a word document using Visual Basic / Visual C# in ASP.NET

I'm looking for options to fill a Word Document from either Visual Basic, or Visual C#. I'm currently using merge fields, and the code below to fill specific fields in a Word Document, but now I've run into a situation where I need tabular data pushed to MS Word. Is there anyway to take data from a grid view (number of rows is dynamic), and import it into a Word Document Table using a merge field or something of that sort? I have to maintain the format of my template doc, and would like to be able to control the layout of the page ..
Dim templateDoc As String = Server.MapPath("\Userfiles\docs\" & location)
Dim mergePath As String = Server.MapPath("\App_Data\Temp\")
Dim mergeFileName As String = location.Replace("/", "_") & ".docx"
Dim mergeDoc As String = mergePath & "\" & mergeFileName
File.Copy(templateDoc, mergeDoc, True)
Using pkg As Package = Package.Open(mergeDoc, FileMode.Open, FileAccess.ReadWrite)
Dim uri As Uri = New Uri("/word/document.xml", UriKind.Relative)
Dim part As PackagePart = pkg.GetPart(uri)
Dim xmlMainXMLDoc As XmlDocument = New XmlDocument()
xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read))
Dim innerXml As String = xmlMainXMLDoc.InnerXml _
.Replace("«Corporate Legal Name»", businessName) _
.Replace("«Address 1»", mailingAddress1) _
.Replace("«Address 2»", mailingAddress2) _
.Replace("«City»", city)
xmlMainXMLDoc.InnerXml = innerXml
Using partWriter As New StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write))
xmlMainXMLDoc.Save(partWriter)
End Using
pkg.Close()
End Using
You can write out in HTML and save it with a .doc extension and Word will handle it gracefully.
Just like my answer for your question regarding Excel, Office writer will work for you here too!

Serialize Linq objects not working

Using the following code:
Private Sub MakeMeSomeXmlBeforeRyanGetsAngry()
Dim db As New MyDBDataContext
Dim customer = From c In db.Customers Select c
Dim dcs As New DataContractSerializer(GetType(Customer))
Dim sb As StringBuilder = New StringBuilder
Dim writer As XmlWriter = XmlWriter.Create(sb)
dcs.WriteObject(writer, customer)
Dim xml As String = sb.ToString
Response.Write(xml)
End Sub
I am attempting to serialize my linq collection of customers. But it keeps throwing
Type 'System.Data.Linq.DataQuery`1[MyDB.Customer]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. See the Microsoft .NET Framework documentation for other supported types.
My issue is that I have already marked the dbml Serialization Mode to UniDirectional and when I check the dbml codebehind all of the DataContract()> and DataMember()> elements are there.
I am not sure how to proceed. I have tried adding various dataloadoptions and setting deferredloading to false, but no luck.
Ideas?
This is working for me with Serialization Mode property of .dbml set to UniDirectional:
Public Shared Function CreateXml(Of T)(ByVal item As T) As String
Dim result As String = ""
Dim memoryStream As New IO.MemoryStream()
Dim serializer As New DataContractSerializer(GetType(T))
serializer.WriteObject(memoryStream, item)
memoryStream.Position = 0
Using reader As New StreamReader(memoryStream)
result = reader.ReadToEnd()
End Using
memoryStream.Close()
Return result
End Function
Dim db As New SerializerDataContext()
Dim questions = db.Questions.ToList()
Dim xmlFileName As String = "D:\\xml_test.xml"
If My.Computer.FileSystem.FileExists(xmlFileName) Then My.Computer.FileSystem.DeleteFile(xmlFileName)
Dim xml As String = XmlHelper.CreateXml(Of List(Of Question))(questions)
My.Computer.FileSystem.WriteAllText(xmlFileName, xml, True)
I think the problem arises because LINQ queries are processed only on demand, and are not serializable. Try to serialize a serializable data type resulting from your LINQ query (array, list, a single item, etc.)
dcs.WriteObject(writer, customer.ToArray)
(I assume you only need to serialize the results of the query, and not the query itself)

Importing a spreadsheet, but having trouble

I have a form that allows a user to import a spreadsheet. This spreadsheet is generally static when it comes to column headers, but now the users want to be able to include an optional column (called Notes). My code crashes when I try to read the column from the spreadsheet if it doesn't exist.
Dim objCommand As New OleDbCommand()
objCommand = ExcelConnection() 'function that opens spreadsheet and returns objCommand
Dim reader As OleDbDataReader
reader = objCommand.ExecuteReader()
While reader.Read()
Dim Employee As String = Convert.ToString(reader("User"))
Dim SerialNUM As String = Convert.ToString(reader("serialno"))
**Dim Notes As String = Convert.ToString(reader("notes"))**
If the spreadsheet contains a Notes column, all goes well. If not, crash. How can I check to see if the Notes column exists in the spreadsheet to avoid the crash?
Change the code to something like this:
[EDIT - changed code logic)
Dim fieldCount = reader.FieldCount
For i = 0 To fieldCount - 1
Dim colName = reader.GetName(i)
If (colName = "notes") Then
Dim Notes As String = reader.GetString(i)
End If
Next i
Perhaps OleDbDataReader.FieldCount could help you program a workaround.

Resources