6

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

3 Answers 3

10

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);
Sign up to request clarification or add additional context in comments.

Comments

2

You have to use [XmlElementAttribute], not [DataContractAttribute], if you wish to use the XML Serializer.

1 Comment

Yes, it were just some WCF generated entities; so they were decorated with the DataContractAttribute
0

Ah, had to use DataContractSerializer, which automatically generates correct XML, including the namespaces.

DataContractSerializer dcs = new DataContractSerializer(typeof(OrderContainer));
//do stuff..
dcs.WriteObject(s, orderContainer);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.