sanika
sanika

Reputation: 79

convert String to XML in VB.NET

Dim filter As String
filter = 'Bal_ln_id = 110 and Bal_ln_id = 100'     
Dim xmldoc As New System.Xml.XmlDocument
xmldoc.LoadXml(filter)

I am simply trying to convert a string in to xml file in VB.net.I am getting an xmlException 'Data at the root level is invalid. Line 1, position 1.'

Am I missing something?

I am expecting the output as

<DocumentElement>
  <DATA_TABLE>
    <BAL_LN_ID>110</BAL_LN_ID>
  </DATA_TABLE>
  <DATA_TABLE>
     <BAL_LN_ID>100</BAL_LN_ID>
  </DATA_TABLE>
</DocumentElement>'

Upvotes: 0

Views: 14796

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

To do this using the XmlTextWriter class, you could do something like this:

Private Function GenerateXml(ByVal ids As List(Of String)) As String
    Dim stringWriter As New StringWriter()
    Dim xmlWriter As New XmlTextWriter(stringWriter)
    xmlWriter.WriteStartDocument()
    xmlWriter.WriteStartElement("DocumentElement")
    For Each id As String In ids
        xmlWriter.WriteStartElement("DATA_TABLE")
        xmlWriter.WriteStartElement("BAL_LN_ID")
        xmlWriter.WriteString(id)
        xmlWriter.WriteEndElement()
        xmlWriter.WriteEndElement()
    Next
    xmlWriter.WriteEndElement()
    xmlWriter.WriteEndDocument()
    Return stringWriter.ToString()
End Function

Then you could use it like this:

Dim ids As New List(Of String)()
ids.Add("110")
ids.Add("100")
Dim xml As String = GenerateXml(ids)

Upvotes: 7

Related Questions