views:

324

answers:

1

I'm looking for a way with C# which I can serialize a class into XML and add a namespace, but define the prefix which that namespace will use.

Ultimately I'm trying to generate the following XML:

<myNamespace:Node xmlns:myNamespace="...">
  <childNode>something in here</childNode>
</myNamespace:Node>

I know with both the DataContractSerializer and the XmlSerializer I can add a namespace, but they seem to generate a prefix internally, with something that I'm not able to control. Am I able to control it with either of these serializers (I can use either of them)?

If I'm not able to control the generation of the namespaces will I need to write my own XML serializer, and if so, what's the best one to write it for?

+3  A: 

To control the namespace alias, use XmlSerializerNamespaces.

[XmlRoot("Node", Namespace="http://flibble")]
public class MyType {
    [XmlElement("chileNode")]
    public string Value { get; set; }
}

static class Program
{
    static void Main()
    {
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("myNamespace", "http://flibble");
        XmlSerializer xser = new XmlSerializer(typeof(MyType));
        xser.Serialize(Console.Out, new MyType(), ns);
    }
}

If you need to change the namespace at runtime, you can additionally use XmlAttributeOverrides.

Marc Gravell
+1 but could I suggest an edit to make it clear that the first parameter in the .Add method is the place where the magic happens for setting the prefix. It wasn't clear to me from the answer until I checked the MSDN docs.
David Hall
fair to assume that there isn't an equivalent with DataContractSerializer? (Just wanting to keep my options open)
Slace
@Slace - yes, I believe it is safe to assume that there **isn't** an equivalent for DCS. Ultimately, DCS isn't intended to give you much control over the output (if you want to control the xml, use `XmlSerializer` - that is its job).
Marc Gravell