Namespaces & Integration

Namespaces

What are Namespaces?

Namespaces in XML are used to avoid element name conflicts by qualifying names with a unique identifier, typically a URI. They allow combining XML documents from different XML vocabularies without name clashes.


Syntax

Declare a namespace with an attribute in the start tag

<root xmlns:prefix="namespaceURI">
  <prefix:element>Content</prefix:element>
</root>
  • xmlns defines the namespace.

  • prefix is a shorthand alias used before element or attribute names.

  • The URI is usually a URL but does not have to point to an actual resource.


Example

<bookstore xmlns:fiction="http://example.com/fiction" xmlns:nonfiction="http://example.com/nonfiction">
  <fiction:book>
    <fiction:title>The Great Novel</fiction:title>
  </fiction:book>
  <nonfiction:book>
    <nonfiction:title>Science Explained</nonfiction:title>
  </nonfiction:book>
</bookstore>

Default Namespace

You can define a default namespace for elements without a prefix

<root xmlns="http://example.com/default">
  <element>Content</element> <!-- belongs to default namespace -->
</root>

Important Notes

  • Namespaces apply to elements and attributes.

  • Prefixes are arbitrary but must be consistent.

  • Namespaces help XML parsers distinguish between elements with the same name but different meanings.

XML with Databases

Using XML with Databases

XML is often used to exchange, store, or transfer data between applications and databases because it is platform-independent and human-readable.


Common Uses

  • Storing XML data: Some databases (e.g., SQL Server, Oracle, MySQL) support XML data types or store XML documents as text.

  • Exporting/Importing: Export database data to XML format or import XML data into databases.

  • Querying XML: Use languages like XPath, XQuery, or SQL/XML extensions to query XML stored in databases.


Examples

1. Storing XML in a Database (MySQL)

CREATE TABLE books (
  id INT PRIMARY KEY,
  data XML
);

INSERT INTO books (id, data) VALUES (
  1,
  '<book><title>XML Guide</title><author>John Doe</author></book>'
);

2. Querying XML Data (SQL Server example)

SELECT
  data.value('(/book/title)[1]', 'NVARCHAR(100)') AS Title,
  data.value('(/book/author)[1]', 'NVARCHAR(100)') AS Author
FROM books;

3. Importing XML into Database

  • Parse XML with application code.

  • Map XML elements to database fields.

  • Insert/update database tables accordingly.

Last updated