I want to write an XML file in the following format

<?xml version="1.0" encoding="utf-8" ?>
<trans>
   <trans eng="string from listbox1" type="string from listbox2"/>
   <trans eng="string from listbox1" type="string from listbox2"/>
  <trans eng="string from listbox1" type="string from listbox2"/>
   <trans eng="string from listbox1" type="string from listbox2"/>
  <trans eng="string from listbox1" type="string from listbox2"/>
   <trans eng="string from listbox1" type="string from listbox2"/>
  <trans eng="string from listbox1" type="string from listbox2"/>
   <trans eng="string from listbox1" type="string from listbox2"/>
   </trans>

I used the following code but the layout is not as above

Dim settings As XmlWriterSettings = New XmlWriterSettings()
        settings.Indent = True

        Using writer As XmlWriter = XmlWriter.Create("D:\Translations", settings)
            ' Begin writing.
            writer.WriteStartDocument()
            writer.WriteStartElement("trans")

            For i = 0 To ListBox1.Items.Count - 1
                writer.WriteElementString("eng", ListBox1.Items(i))
                writer.WriteElementString("type", ListBox2.Items(i))
            Next
            writer.WriteEndElement()
        End Using

Using the above code I get the XML file as such

<?xml version="1.0" encoding="utf-8"?>
<trans>
  <eng>string</eng>
  <type>string</type>
  <eng>string</eng>
  <type>string</type>
  <eng>string</eng>
  <type>string</type>
  <eng>string</eng>
  <type>string</type>
  </trans>

Recommended Answers

All 2 Replies

That's because "eng" and "type" are attributes, not elements.

Here's a bit fixed version:

Dim settings As XmlWriterSettings = New XmlWriterSettings()
Dim writer As XmlWriter
Dim i As Integer ' i was undeclared variable
settings.Indent = True

writer = XmlWriter.Create("D:\Translations", settings)
' Begin writing.
writer.WriteStartDocument()
' Start tag for the file
writer.WriteStartElement("translation")

For i = 0 To ListBox1.Items.Count - 1
    writer.WriteStartElement("trans") ' Start element
    ' ListBox.Items(i) is of type Object, you have to cast it to String type
    writer.WriteAttributeString("eng", "", ListBox1.Items(i).ToString()) ' First attribute
    writer.WriteAttributeString("type", "", ListBox2.Items(i).ToString()) ' Second attribute
    writer.WriteEndElement() ' Close element
Next i

writer.WriteEndElement() ' Close start tag
writer.WriteEndDocument() ' Close document
writer.Close() ' Close stream (=file)

HTH

oh! I should have known it, thanks a lot :D n i am quite new to vb programming hehe

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.