When you are planning to create your own XML document, you need to remember and follow some rules:
– XML documents must start with an XML declaration like <?xml version=”1.0″?>. This signals that the document contains XML and indicates any special text encoding. However, many XML parsers work fine even if this detail is omitted.
– XML elements are composed of a start tag (like <Title>) and an end tag (like </Title>). Content is placed between the start and end tags. If you include a start tag, you must also include a corresponding end tag. The only other option is to combine the two by creating an empty element, which includes a forward slash at the end and has no content (like <Title />).
– Whitespace between elements is ignored. That means you can freely use tabs and hard returns to properly align your information.
– You can use only valid characters in the content for an element. You can’t enter special characters, such as the angle brackets (< >) and the ampersand (&), as content. Instead, you’ll have to use the entity equivalents (such as < and > for angle brackets, and & for the ampersand). These equivalents will be automatically converted to the original characters when you read them into your program with the appropriate .NET classes.
– XML elements are case sensitive, so <ISBN> and <isbn> are completely different elements.
– All elements must be nested in a root element. As soon as the root element is closed, the document is finished, and you cannot add anything else after it. For example your root element could be <BooksList> and your elements could be placed between couples of start tag <Book> and end tag </Book>. If you omit the <BooksList> element and start with a <Book> element, you’ll be able to enter information for only one book, because as soon as you add the closing </Book>, the document is complete.
– Every element must be fully enclosed. In other words, when you open a sub-element, you need to close it before you can close the parent. <Book><ISBN></ISBN></Book> is valid, but <Book><ISBN></Book></ISBN> isn’t. As a general rule, indent when you open a new element, because this will allow you to see the document’s structure and notice if you accidentally close the wrong element first.
As long as you meet these rules, your XML document can be parsed and displayed as a basic tree. The next example shows a XML document.
<?xml version=”1.0″?>
<BooksList>
<Book>
<ISBN-13> 978-0545139700</ISBN-13>
<Title>Harry Potter and the Deathly Hallows </Title>
<Author>J.K. Rowling</Author>
<Price>14.99</Price>
<Available>True</Available>
</Book>
<Book>
<ISBN-13>978-1451648539</ISBN-13>
<Title> Steve Jobs</Title>
<Author>Walter Isaacson</Author>
<Price>17.88</Price>
<Available>True</Available>
</Book>
<Book>
<ISBN-13>978-0765309761</ISBN-13>
<Title>Tunnel Vision</Title>
<Author>Gary Braver</Author>
<Price>17.15</Price>
<Available>False</Available>
</Book>
</BooksList>