0

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?

1 Answer 1

1

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")
    )
);
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.