Tristan
Tristan

Reputation: 65

How can I create an XML file in Visual Basic?

I was asked to write some code to interface with the Wi-Flight Api in visual basic. I already have code to login and interface with the API.

I am writing some sample code to submit a reservation. To do this, I need to create an xml file and fill it with the appropriate data which will be simply be entered in TextFields for this sample code.

I have found various snippets of code on the internet to create basic files that look like (source):

    <?xml version="1.0" encoding="utf-8"?>
    <Employees>
      <Employee>
        <ID>1</ID>
        <FirstName>Prakash</FirstName>
        <LastName>Rangan</LastName>
        <Salary>70000</Salary>
      </Employee>
      <Employee>
        <ID>5</ID>
        <FirstName>Norah</FirstName>
        <LastName>Miller</LastName>
        <Salary>21000</Salary>
      </Employee>
      <Employee>
        <ID>17</ID>
        <FirstName>Cecil</FirstName>
        <LastName>Walker</LastName>
        <Salary>60000</Salary>
      </Employee>
    </Employees>

Now, I need to create an xml file that look like this.

It requires me to put things like

    <reservation name="unique-name">

I have not found any way to add the name="unique-name" part to the XML file. I am looking for a way to do this.

Upvotes: 0

Views: 3778

Answers (2)

Victor Zakharov
Victor Zakharov

Reputation: 26454

Very easy to do using XDocument/XElement:

Dim v As XElement = <reservation/>
'or Dim v As XElement = XElement.Parse("<reservation/>")
'or Dim v As XElement = XElement.Load("pathToFile")
v.SetAttributeValue("name", "unique-name")
Debug.WriteLine(v.ToString) 'prints <reservation name="unique-name" />

Upvotes: 1

collapsar
collapsar

Reputation: 17258

no offence, but don't you think you might be interested in the documentation of XmlWriter ? know your tools ...

xmlWriter.WriteAttributeString( "name", sUniqueName ) is your friend, assuming that sUniquename holds the, well, unique name needed.

Upvotes: 0

Related Questions