Tuesday, March 31, 2009

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();

 

5 comments:

  1. Many thanks. Just the fix I was looking for.

    ReplyDelete
  2. Great work! Thanks for saving my tyme!
    Good luck.

    ReplyDelete
  3. Thanks a million. My problem got resolved

    ReplyDelete