Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use XmlSerializer to add a namespace without a prefix

I want my output to look like this

<OrderContainer xmlns="http://blabla/api/products" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

So I added the following to my XmlSerializer

XmlSerializer x = new XmlSerializer(typeof(OrderContainer));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "http://blabla/api/products");
ns.Add("i", "http://www.w3.org/2001/XMLSchema-instance");
// do stuff..
x.Serialize(stream, orderContainer, ns);

But now I get

<OrderContainer xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

So how do I edit the default namespace?


My object definition is like:

[System.Runtime.Serialization.DataContractAttribute(Name="OrderContainer", Namespace="http://blabla/api/products")]
[System.SerializableAttribute()]
public partial class OrderContainer
like image 766
Jan Jongboom Avatar asked Dec 07 '09 16:12

Jan Jongboom


1 Answers

You could use the XmlSerializer constructor which takes a default namespace in addition to the type you want to serialize:

var x = new XmlSerializer(
    typeof(OrderContainer), 
    "http://blabla/api/products");
var ns = new XmlSerializerNamespaces();
ns.Add("i", "http://www.w3.org/2001/XMLSchema-instance");
x.Serialize(stream, orderContainer, ns);
like image 197
Darin Dimitrov Avatar answered Sep 21 '22 16:09

Darin Dimitrov