C# .Net – Writing multiple namespaces with XmlWriter


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" );

 

Advertisements

Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: