Friday 12 October 2007

Build custon XML from database using XmlTextWriter

Simple way to out put as xml is using
dim ds as dataset
ds.WriteXml("C:\test\HCSReports\createdXML\employee.xml")

if you need custom xml output then use the below function



Imports System.Xml
Imports System.Xml.XPath
Imports System.Xml.Xsl

Public Function CreateCustomXML(ByVal objDataSet As DataSet) As String

Dim intI As Integer
Dim strPath As String

'create an instance of the XmlTextWriter object
Dim objWriter As XmlTextWriter = Nothing

Try

' location to the XML file to write
strPath = strFilepath & Now.Second & ".xml"

objWriter = New XmlTextWriter(strPath, System.Text.Encoding.Default)

' start writing the XML document
objWriter.WriteStartDocument()

' write a comment in our XML file
objWriter.WriteComment("PanelManagerMonthlyReport")

' starting with the root element i.e. "movies"
objWriter.WriteStartElement("PMMonthlyReport")

'Set data to XML tags
If objDataSet.Tables(0).Rows.Count > 0 Then
For intI = 0 To objDataSet.Tables(0).Rows.Count - 1
objWriter.WriteStartElement("Period") ' output the "Employee" element
objWriter.WriteElementString("Name", objDataSet.Tables(0).Rows(intI).Item("Name").ToString)
objWriter.WriteElementString("Prospects", objDataSet.Tables(0).Rows(intI).Item("Prospects").ToString)
objWriter.WriteElementString("Instructions", objDataSet.Tables(0).Rows(intI).Item("Instructions"))
objWriter.WriteElementString("Cancellations", objDataSet.Tables(0).Rows(intI).Item("Cancellations"))
objWriter.WriteElementString("Completions", objDataSet.Tables(0).Rows(intI).Item("Completions"))
objWriter.WriteElementString("Quotes", objDataSet.Tables(0).Rows(intI).Item("Quotes"))
objWriter.WriteElementString("IntroducerUserRegistrations", objDataSet.Tables(0).Rows(intI).Item("IntroducerUserRegistrations"))
objWriter.WriteElementString("IntroducerUserTrained", objDataSet.Tables(0).Rows(intI).Item("IntroducerUserTrained"))
objWriter.WriteElementString("SolicitorAppsIssued", objDataSet.Tables(0).Rows(intI).Item("SolicitorAppsIssued"))
objWriter.WriteElementString("SolicitorContractsReturned", objDataSet.Tables(0).Rows(intI).Item("SolicitorContractsReturned"))
objWriter.WriteElementString("Index", objDataSet.Tables(0).Rows(intI).Item("Index"))
objWriter.WriteEndElement() ' close "Employee" element
Next
End If

' end the "Menu" element
objWriter.WriteEndElement()

' flush and write XML data to the file
objWriter.Flush()

Return strPath
Catch ex As Exception
Return False
Finally
' clear up memory
objWriter.Close()
objWriter = Nothing
objDataSet = Nothing
End Try
End Function

No comments: