C# ASP.NET SQL SERVER

The prefix cannot be redefined from within the same start element tag

The following snippet of code had me stumped for a while:

XDocument xDoc = new XDocument(new XDeclaration("1.0", 
                                       
"utf-8", "yes"),
   
new XComment("This is a comment"),
   
new XElement("elementName",
       
new XAttribute("xmlns", "http://fake/namespace"),
       
new XAttribute("version", "1.00"),
       
new XElement("innerelement",
           
new XAttribute("myAttribute", "att_value"))
           
));

// The prefix '' cannot be redefined from ''
// to 'http://fake/namespace'
// within the same start element tag..
string test = xDoc.ToString();

I was getting a  "The prefix '' cannot be redefined from '' to 'http://fake/namespace' within the same start element tag.." when running this.

The solution is to define the namespace before creating the XML document and prefixing this namespace to all elements that you create. Here is the working code.

XNamespace xn = "http://fake/namespace";

XDocument xDoc = new XDocument(new XDeclaration("1.0",
                                       
"utf-8", "yes"),
   
new XComment("This is a comment"),
   
new XElement(xn + "elementName",

       
new XAttribute("version", "1.00"),
       
new XElement(xn + "innerelement",
           
new XAttribute("myAttribute", "att_value"))
           
));
string test = xDoc.ToString();

 

» Similar Posts

  1. Optimizing a custom Trim() function in C#
  2. LINQ to XML Notes
  3. Adding classes to elements to assist jQuery

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://guyellisrocks.com/trackback.ashx?id=150

» Comments

  1. Martin Evans avatar

    Many thanks. Just the fix I was looking for.

    Martin Evans — May 7, 2009 10:43 AM
  2. Ofer avatar

    Thanks a lot !!

    Ofer — July 9, 2009 4:07 AM
  3. Andrey Klimenko avatar

    Great work! Thanks for saving my tyme!

    Good luck.

    Andrey Klimenko — September 15, 2009 3:26 PM
  4. Srini avatar

    Thanks a million. My problem got resolved

    Srini — October 2, 2009 2:30 PM

» Leave a Comment