Archive for the ‘XmlWriter’ Category

C# .Net – Writing multiple namespaces with XmlWriter

March 23, 2010

I ran into an error yesterday when writing name spaces using XmlWriter.

I started out trying to write the namespace attributes using WriteAttributeString.

writer.WriteStartElement( "Page" );
writer.WriteAttributeString(
    "xmlns",
    "http://schemas.microsoft.com/winfx/2006/xaml/presentation" );
writer.WriteAttributeString(
    "xmlns:x",
    "http://schemas.microsoft.com/winfx/2006/xaml/presentation" );

When run, XmlWriter threw an exception :-

The prefix ” cannot be redefined from ” to ‘http://schemas.microsoft.com/winfx/2006/xaml/presentation’ within the same start element tag.

After a digging around I found the solution was output the namespaces in the following way:-

writer.WriteStartElement(
    "Page",
    "http://schemas.microsoft.com/winfx/2006/xaml/presentation" );
writer.WriteAttributeString(
    "xmlns",
    "x",
    null,
    @"http://schemas.microsoft.com/winfx/2006/xaml" );