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

 

6 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
  4. I am having a similar problem. I need the following element written with the attributes. Like this:
    <EmployerTPASeparationResponseCollection xmlns="https://uidataexchange.org/schemas" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://uidataexchange.org/schemas SeparationResponse.xsd ">
    Here is my code:
    XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
    XNamespace xmlns = "https://uidataexchange.org/schemas";
    XElement EmployerTPASeparationResponse = null;
    XElement EmployerTPASeparationResponseCollection = new XElement("EmployerTPASeparationResponseCollection", new XAttribute("xmlns", xmlns), new XAttribute(XNamespace.Xmlns + "xsi", xsi), new XAttribute(xsi + "schemaLocation", "https://uidataexchange.org/schemas SeparationResponse.xsd"));
    XDocument doc = new XDocument(
    new XDeclaration("1.0", null, "yes"), EmployerTPASeparationResponseCollection);
    I can't seem to get around this. Any help appreciated!
    thank,
    zach

    ReplyDelete