8

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">
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?

pnuts
  • 58,317
  • 11
  • 87
  • 139

2 Answers2

12

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
  • 19,739
  • 7
  • 52
  • 88
0

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
  • 160,644
  • 26
  • 247
  • 397
  • 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 Mar 23 '10 at 17:05
  • I wanted the xmlns in the declaration to ease for end users that'll edit the xml by hand some day. –  Mar 24 '10 at 10:01