Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top