Talk, talk and more talk about BizTalk

Changing / Removing document namespaces

I recently ran into a requirement to both transmit and receive documents using “Plain Old Xml”. The system we were integrating was not able to understand the concept of namespaces in an Xml document, but BizTalk requires them, as messages are determined by the combination of a document’s Namespace and Root Node.

The solution was two-fold. For incoming messages, we “inject” a pre-determined namespace into the document as soon as it hits BizTalk. For outbound messages, we strip out all namespaces and alias’ just as we are sending it. The best was to do this is using a Pipeline Component.

There are a number of components and methods out there for adding a namespace to an inbound messages, see here and here.  I ended up re-using a sample I found on CodePlex.

To remove namespaces from the outbound messages, I massaged the content of the message using a Regular Expression, and some simple text replacement:

private static string RemoveNamespace(XmlDocument xdoc)
  // Regex to search for either xmlns:nsN="..." or xmlns="..."
  const string pattern = @"xmlns:?(\w+)?=""[\w:/.]*""";
  string xml = xdoc.OuterXml;

  Regex replace = new Regex(pattern);
  // Replace all occurances of the namespace declaration
  string temp = replace.Replace(xml, String.Empty);
  foreach (Match match in replace.Matches(xml))
    // Loop through each Match in the Regex, this gives us the namespace aliases found
    if (match.Success && match.Groups.Count > 1)
      if (!String.IsNullOrEmpty( match.Groups[1].Value))
        Regex alias = new Regex(@"\b" + match.Groups[1].Value + ":");
        // Replace all occurances of the
        temp = alias.Replace(temp, String.Empty);
  return temp;

The regular expression identifies namespace declarations, whether they declare an alias or not.  We then iterate all of the matched aliases, removing them from the target xml document.

Edit: I have added a link to cut-down sample project, detailing exactly how the pipeline component should be implemented.  Click here to download.

Edit2: Modified the regex pattern slightly so it also accounts for elements declared in the “empty” namespace.


June 26, 2012 Posted by | BizTalk, Pipeline | , , | 3 Comments