-
Notifications
You must be signed in to change notification settings - Fork 7
How to Write XML
XML stands for eXtensible Markup Language. It's designed to store and transport data as well as be both human- and machine-readable.
Your XML file should always start with this line:
<?xml version="1.0" encoding="UTF-8"?>
XML is a collection of elements, which are comprised of opening and closing tags. Tag names are case-sensitive. An element includes the open tag, the close tag, and everything inside of it.
-
<Name>
denotes the open tag. -
</Name>
denotes the close tag. -
<Name/>
denotes an open and close tag and is a whole element. -
<Name></Name>
denotes an open and close tag and is a whole element.
All open tags must be closed by the end of the file or else the XML cannot be read.
Elements can be placed inside of each other like such. Elements can also have values inside them.
<?xml version="1.0" encoding="UTF-8"?>
<ItemList>
<ItemElement>
<Value/>
<AnotherValue>0</AnotherValue>
</ItemElement>
<ItemElement>
<Value/>
<AnotherValue>5</AnotherValue>
</ItemElement>
</ItemList>
Tags must always be opened and closed in first-in last-out order. For example:
<?xml version="1.0" encoding="UTF-8"?>
<OutsideTag>
<InsideTag>SomeElementInnerText</OutsideTag>
</InsideTag>
This is incorrect.
<?xml version="1.0" encoding="UTF-8"?>
<OutsideTag>
<InsideTag>SomeElementInnerText</InsideTag>
</OutsideTag>
While this is correct.
Attributes are created by declaring and defining a variable within an element's open tag. Attribute values must be defined within quotes. Attribute names are case-sensitive. Both of the examples below are correct.
<OpenTag AttributeName="AttributeValue"></OpenTag>
<OpenCloseTag AnotherName="AnotherValue"/>
Multiple attributes can be assigned to the same element.
<Food Name="Apple" Color="Red"/>
Comments are defined by the opening tag of <!--
and the closing tag of -->
. Everything within a comment is ignored by XML when being read. Comments cannot be started within a tag. Here is an example:
<?xml version="1.0" encoding="UTF-8"?>
<Root>
<!--This is a comment-->
<!--This comment stretches across multiple lines
<IgnoredOpenTag>
The comment is closed here-->
</Root>
Escape codes are necessary in order to use certain characters when they already have another use as defined by XML. Escape codes are defined by an opening &
and a closing ;
. Below are all of the relevant escape codes.
Code | Character |
---|---|
" |
" (Double-quote) |
& |
& (Ampersand) |
' |
' (Single-quote) |
< |
< (Less than) |
> |
> (Greater than) |
|
Line break |
&#nnnn; |
Decimal Unicode |
&#xhhhh; |
Hex Unicode |