DEV Community

Cover image for Understanding XML Namespaces and How to Remove Them Safely
kandz
kandz

Posted on Originally published at tools.kandz.me

Understanding XML Namespaces and How to Remove Them Safely

XML namespaces are a mess to remove. One wrong regex and you break the entire document structure. You leave orphaned colons. You accidentally strip actual data.

In this guide, we'll look at what namespaces are, why they cause problems, and how to strip them safely using code.


What is an XML Namespace?

An XML namespace is a way to avoid naming conflicts. If you combine XML from different sources, you might have two different elements with the same name but different meanings. Namespaces fix this by adding a unique prefix.

Without namespaces:

<table>Wooden dining table</table>
<table>Database table</table>
Enter fullscreen mode Exit fullscreen mode

With namespaces:

<furniture:table xmlns:furniture="http://example.com/furniture">
  Wooden dining table
</furniture:table>

<db:table xmlns:db="http://example.com/database">
  Database table
</db:table>
Enter fullscreen mode Exit fullscreen mode

The xmlns:furniture attribute defines the namespace. The URI doesn't have to be a working web address β€” it's just a unique string that acts as a global identifier.


Why Namespaces Cause Problems

Namespaces are great for complex systems, but they make XML messy.

You end up with long prefixed tags like <soap:Envelope> and <soap:Body> everywhere. If you're processing data and don't care about the namespace, it just gets in the way. You have to strip it out before you can parse the data easily.


The Dangerous Way (Don't Do This)

Most people try to use regex:

xmlString.replace(/xmlns(:\w+)?="[^"]*"/g, '')
Enter fullscreen mode Exit fullscreen mode

This removes the namespace declarations. But it doesn't remove the prefixes from the tags.

Then they try:

xmlString.replace(/<(\w+):/g, '<$1')
Enter fullscreen mode Exit fullscreen mode

This removes the prefix from opening tags. But it doesn't remove the prefix from closing tags. And it doesn't handle attributes with prefixes.

The result is broken XML that no parser will accept.


The Safe Way (JavaScript)

The only safe way to remove namespaces is to parse the XML into a DOM, traverse every node, and rebuild it without the namespaces.

function removeNamespaces(xmlString) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(xmlString, "application/xml");

  // Check for parsing errors
  const parseError = doc.querySelector("parsererror");
  if (parseError) throw new Error("Invalid XML");

  function processNode(node) {
    if (node.nodeType === Node.ELEMENT_NODE) {
      // Create a new element without the namespace prefix
      const localName = node.localName;
      const newElement = doc.createElement(localName);

      // Copy attributes, stripping namespaces
      Array.from(node.attributes).forEach(attr => {
        if (!attr.name.startsWith("xmlns")) {
          const attrLocalName = attr.localName;
          newElement.setAttribute(attrLocalName, attr.value);
        }
      });

      // Process children
      Array.from(node.childNodes).forEach(child => {
        const newChild = processNode(child);
        if (newChild) newElement.appendChild(newChild);
      });

      return newElement;
    } else if (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.CDATA_SECTION_NODE) {
      // Return a clone of text or CDATA nodes
      return node.cloneNode();
    }
    return null;
  }

  const newDoc = document.implementation.createDocument(null, null, null);
  const root = processNode(doc.documentElement);
  newDoc.appendChild(root);

  const serializer = new XMLSerializer();
  return serializer.serializeToString(newDoc);
}
Enter fullscreen mode Exit fullscreen mode

This handles:

  • Opening tags
  • Closing tags
  • Attributes with prefixes
  • Namespace declarations on any element
  • Nested namespaces that override parent namespaces

The No-Code Way

If you need to strip xmlns prefixes and definitions from an XML document while preserving the tag structures, I built a free XML Namespace Remover that runs entirely in your browser.

What it does:

  • Parses the XML into a DOM structure safely
  • Strips xmlns prefixes and definitions
  • Preserves tag structures perfectly
  • Outputs clean, namespace-free XML

Why it's useful:

  • No installation
  • No upload (100% client-side)
  • Handles nested namespaces

Try It

XML Namespace Remover

100% client-side. Nothing uploaded.


What's your use case for stripping namespaces? SOAP APIs, legacy system integrations, or something else? Let me know in the comments.

Top comments (0)