views:

289

answers:

2

I'm trying to convert a xml document from one format to another and while doing this I've found that I need to insert multiple xmlns declarations to the root element.

Example:

<?xml version="1.0" encoding="utf-8" ?>
<Template xmlns="http://tempuri.org/TemplateBase.xsd" xmlns:TYPES="http://tempuri.org/TemplateTypes.xsd"&gt;
some content
<Template>

The reason of all this is that I've divided the XSD schema into multiple XSD in order to reuse the general types in this case.

Well, what I want to do now is to write this xml with a XmlTextWriter but I can't write the xmlns attribute for the TYPES.

What I've tried so far is:

XmlWriter xmlWriter = XmlWriter.Create(filename, settings);  
xmlWriter.WriteStartElement("Template", "http://tempuri.org/TemplateBase.xsd");
xmlWriter.WriteAttributeString("xmlns", "TYPES", "http://tempuri.org/TemplateTypes.xsd", XmlSchema.InstanceNamespace);

When I execute this code I get the following exception:
System.ArgumentException: Prefix "xmlns" is reserved for use by XML..

Does anyone have any cure to my current headache?

A: 

It's very simple. Don't write the xmlns attributes.

Instead, you should be writing your attributes and elements in the namespace they belong in. XmlWriter will take care of the namespace declarations (xmlns attributes) on its own.

John Saunders
This will produce valid XML, but I think you get the full namespace URI embedded in every XML element, so this will lead to *very* big output files.
Doc Brown
I wanted the xmlns in the declaration to ease for end users that'll edit the xml by hand some day.
Andreas Westling
A: 

Use

xmlWriter.WriteAttributeString("xmlns", "TYPES", 
    null, "http://tempuri.org/TemplateTypes.xsd");

instead of

 xmlWriter.WriteAttributeString("xmlns", "TYPES", 
    "http://tempuri.org/TemplateTypes.xsd", XmlSchema.InstanceNamespace);

This should give you the desired output.

Doc Brown
Thanks Doc, that did the trick!
Andreas Westling