Search code examples
c#xmlxml-namespaces

The prefix " cannot be redefined from " to <url> within the same start element tag


I'm trying to generate the following xml element using C#.

<Foo xmlns="http://schemas.foo.com" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://schemas.foo.com
 http://schemas.foo.com/Current/xsd/Foo.xsd">

The problem that I'm having is that I get the exception:

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

This is my c# code:

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XElement foo = new XElement("Foo", new XAttribute("xmlns", "http://schemas.foo.com"),
                                   new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
                                   new XAttribute(xsi + "schemaLocation", "http://schemas.foo.com http://schemas.foo.com/Current/xsd/Foo.xsd"));

How can I fix this? I'm trying to send the generated xml as the body of a SOAP message and I need it to be in this format for the receiver.

EDIT: I found my answer on another question. Controlling the order of XML namepaces


Solution

  • You need to indicate that the element Foo is part of the namespace http://schemas.foo.com. Try this:

    XNamespace xNamespace = "http://schemas.foo.com";    
    XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
    XElement foo = new XElement(
        xNamespace + "Foo", 
        new XAttribute("xmlns", "http://schemas.foo.com"),
        new XAttribute(XNamespace.Xmlns + "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
        new XAttribute(xsi + "schemaLocation", "http://schemas.foo.com http://schemas.foo.com/Current/xsd/Foo.xsd")
        );