1. Computing & Technology

Discuss in my forum

Converting an XML File to be Well-Formed

Learn How to Write Well-Formed and Valid XML

By , About.com Guide

Sometimes it's easier to understand how to write well-formed XML by seeing an example. The Web Writer newsletter is written using a form of XML - I call it AML or About Markup Language (go figure!). Here is a sample "AML" file. While this is a working document, it is not actually a well-formed or valid XML document.

Well-Formed

There are some specific rules to create a well-formed XML document:

  • The XML declaration must come first in every document.
  • Comments are not valid within a tag. Comments may not contain two hyphens in a row, other than the beginning and end of the comment.
  • Tags must have an end tag, or be closed within the singleton tag itself, for example <br />.
  • All attributes of tags must be quoted, preferably double quotes unless the attribute itself contains a double quote.
  • Every XML document must contain one element that completely contains all the other elements.

There are only two problems with the document that make it not well-formed:

  1. The first thing that the AML document needs is an XML declaration statement.
    <?xml version="1.0"?>
  2. The other problem is that there is no one element that completely encloses all the other elements. To fix this, I'll add an external container element:
    <newsletter></newsletter>

Making those two simple changes (and ensuring that all the elements contain only CDATA) will turn the non well-formed document into a well-formed document.

Next page > Now Make it Valid > Page 1, 2

Previous Features

©2012 About.com. All rights reserved.

A part of The New York Times Company.