I need multiple xmlns elements in an element with the XmWriter

user300112 picture user300112 · Mar 23, 2010 · Viewed 7k times · Source

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?

Answer

Doc Brown picture Doc Brown · Mar 23, 2010

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.