XML Elements:
Defining and Using Elements in XML:
Elements are the fundamental building blocks of an XML document.
an element consists of:
- A start tag
- Content (which can be other elements, text, or both)
- An end tag
Example:
<book>
<title>XML Fundamentals</title>
<author>John Smith</author>
<price>29.99</price>
</book>
In this example, <book> is an element containing three child elements: <title>, <author>, and <price> per book. Each child element also contains its own content.
Nesting and Hierarchy of Elements:
Nesting refers to placing elements within other elements, creating a hierarchical structure.
This hierarchy is useful in presenting the relationship that exists between different pieces of data.
Example:
<library>
<book>
<title>XML Fundamentals</title>
<author>John Smith</author>
<price>29.99</price>
</book>
<book>
<title>Advanced XML</title>
<author>Jane Doe</author>
<price>39.99</price>
</book>
</library>
In this example:
- This <library> is the root element.
- It contains two <book> elements.
- Each <book> element contains <title>, <author>, and <price> elements.
This structure is thus a library, which consists of several books each of which possess a title and an author, as well as a price.
Empty Elements and Self-Closing Tags:
Empty elements do not have any content between the start and end tags.
Rather than write an opening tag then an immediate close tag, you may use the self close tag.
Example:
<bookstore>
<book>
<title>XML Fundamentals</title>
<author>John Smith</author>
<price>29.99</price>
<available/>
</book>
</bookstore>
In this example:
The declaration specifies that the XML version is 1.0 and the character encoding is UTF-8.
- The <available/> is an empty element represented by a self-closing tag.
- It means it’s just informs that the book is available without giving any other information.