Kirk Evans Blog

.NET From a Markup Perspective

How Do I Remove Namespaces Using XSLT?

How Do I Remove Namespaces Using XSLT?

Rate This
  • Comments 12

I have seen this question several times lately...  “How do I use XSLT to remove the namespace bindings and namespace prefixes from an input XML document?” 

While you can remove namespaces using XSLT, you have to consider the use case and decide if you really want to do this in your XSLT or not. The easiest way to do this using the System.Xml classes is to create a custom XmlTextWriter that simply does not emit the namespace URI or the namespace prefix.

using System;
using System.Xml;

namespace XmlAdvice.Xml
{
 
public class XmlNoNamespaceWriter : System.Xml.XmlTextWriter
 {
  
public XmlNoNamespaceWriter(System.IO.TextWriter writer): base(writer)
  {   
  }

  
public XmlNoNamespaceWriter(System.IO.Stream stream, System.Text.Encoding encoding) : base(stream,encoding)
  {
  }

  
public override void WriteStartElement(string prefix, string localName, string ns)
  {
   
base.WriteStartElement(null,localName,null);
  }

  
public override void WriteStartAttribute(string prefix, string localName, string ns)
  {
   
base.WriteStartAttribute(null,localName,null);
  }
 }
}

Using this class in an XSLT transformation is fairly simple:

private void Page_Load(object sender, System.EventArgs e)
{
 System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(Server.MapPath("xmlfile1.xml"));
 System.Xml.Xsl.XslTransform trans = new System.Xml.Xsl.XslTransform();
 trans.Load(Server.MapPath("xsltfile1.xslt"),new System.Xml.XmlUrlResolver());
 XmlNoNamespaceWriter writer = new XmlNoNamespaceWriter(Response.OutputStream, System.Text.Encoding.UTF8 );
 trans.Transform(doc,null,writer,new System.Xml.XmlUrlResolver());
 writer.Flush();
 writer.Close();
}

However, if you only want to remove the namespaces from XML and leave the XML intact (i.e., no transformation is really needed), then this is even simpler:

private void Page_Load(object sender, System.EventArgs e)
{
 System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(Server.MapPath("xmlfile1.xml"));
 XmlNoNamespaceWriter writer = new XmlNoNamespaceWriter(Response.OutputStream, reader.Encoding );
 writer.WriteNode(reader,true);
 reader.Close();
 writer.Flush();
 writer.Close();
}
Page 1 of 1 (12 items)
Leave a Comment
  • Please add 1 and 5 and type the answer here:
  • Post
Translate This Page
Search
Archive
Archives