1

How can I define a default namespace in XML using the XMLTextWriter?

I want my XML to look like this:

<myXml xmlns:nss="http://my/location/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://my/location/">

xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteStartElement("myXml");
xmlTextWriter.WriteAttributeString("xmlns", "nss", null, statusNamespace);
xmlTextWriter.WriteAttributeString("xmlns", "xsi", null, xsiSchemaNamespace);

How can I get the xmlns default without any prefix?

If I add the following line additionally, I get the prefix cannot be redefined from to "http://my/location/"

xmlTextWriter.WriteAttributeString("xmlns", null, null, statusNamespace);
2
  • WriteAttributeString(null, "xmlns", null, statusNamespace) ? Commented Feb 9, 2015 at 10:31
  • No, I still get the same error message! The prefix cannot be redefined with the same start element tag! Commented Feb 9, 2015 at 10:52

1 Answer 1

1

You should generally prefer to use the overloads which accept namespaces directly, rather than manually trying to apply namespaces via attributes.

This code:

var myWriter = XmlTextWriter.Create("Blah1.xml");
myWriter.WriteStartDocument();
myWriter.WriteStartElement("myXml", "http://my/location/");
myWriter.WriteAttributeString("xmlns", "nss", null, "http://my/location/");
myWriter.WriteAttributeString("xmlns", "xsi", null,
         "http://www.w3.org/2001/XMLSchema-instance");
myWriter.Close();

Generates:

<?xml version="1.0" encoding="utf-8"?>
<myXml xmlns:nss="http://my/location/" 
mlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://my/location/" />

(With spaces added for readability)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.