How to Write Your First XML Document

Illustration of three men and computer with XML code

 Doug Ross / Getty Images

Writing in XML is not difficult. The XML language is a skill that most anyone can learn. The hardest part of learning anything new is getting started. Creating a document in a computer language is best done step-by-step. Working through the basics of writing in XML will help you develop a routine. Once you write the first XML file, you will see the system is easy and flexible. The primary purpose of XML is to contain data that can be accessed by the processor. Take a look at this small inventory list for a store:

Inventory

Bikes

  • 24-inch Boys Mountain Bike $200
  • 24-inch Boys Cruiser Bike $150

Skateboards

  • Acme Sportsmen Skateboard $75
  • Deluxe Boys Skateboard $35

Write a Declaration Statement

Declarations provide information to the browser, such as language. A barebones XML declaration statement only requires the language and version. This is enough to establish the page as an XML document. Additional options include encoding and standalone status.

Create a Root Element

The root element is a container that holds all other elements. It is the first elemental tag for your XML file.

Get in the habit of closing your elements as you write them. XML requires closing tags for all elements. Writing both tags at the same time ensures well-formed code and helps to control the structure of the XML.

Establish the Child Elements

Child elements nest inside the root element. In an inventory listing, you might create sections for different inventory categories. In the example, we have bikes and skateboards.

  
  
  
  

Add Subchild Elements to Hold the Data

Subchild elements nest inside of child elements to hold data you want to store. For this example, there are two models of bikes and two of skateboards. One straightforward format for this list involves nesting additional elements inside the subchild to provide more information for each model, such as price.

 
24-inch Boys Mountain Bike
$200.00

24-inch Boys Cruiser Bike
$150.00



Acme Sportsmen Skateboard
$75.00

Deluxe Boys Skateboard
$35.00

This is just one way to work the XML code for this file. Another method would involve using attributes with the elements to identify each section. The advantage of attributes comes when you create formatting for the XML code.

Format
mla apa chicago
Your Citation
Ferrara, Darla. "How to Write Your First XML Document." ThoughtCo, Dec. 6, 2021, thoughtco.com/write-first-xml-document-3466592. Ferrara, Darla. (2021, December 6). How to Write Your First XML Document. Retrieved from https://www.thoughtco.com/write-first-xml-document-3466592 Ferrara, Darla. "How to Write Your First XML Document." ThoughtCo. https://www.thoughtco.com/write-first-xml-document-3466592 (accessed April 19, 2024).