Kai
Kai

Reputation: 780

XML add both a named and a default namespace error

I want to create an XML file with two namespaces for my root element, one default and one named. Following is my code:

 var testdoc= new XDocument(
       new XDeclaration("1.0", "utf-8", "yes"),
       new XElement("Document",
            new XAttribute("xmlns", "namespace1"),
            new XAttribute(XNamespace.Xmlns + "xsi", "namespace2"),
            new XElement("sampleElem", "content")
       )
 );

This generates the following error:

the prefix for "namespace2" can not be redefined within the same code for starting a new element.

I understand the error, but I do not understand why I get it (as the prefix name is not the same). Anyone know the correct way to get the desired result?

Upvotes: 0

Views: 49

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14231

Because in this line new XElement("Document", you have already created an element with a namespace by default. Specifying the attribute you are trying to override it.

Do this

XNamespace ns = "namespace1";

var testdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement(ns + "Document",
        new XAttribute(XNamespace.Xmlns + "xsi", "namespace2"),
        new XElement("sampleElem", "content")
    )
);

Upvotes: 1

Related Questions