22

I am trying to generate an XML document that contains the default namespace without a prefix using XmlSerializer, e.g.

<?xml version="1.0" encoding="utf-8" ?>
<MyRecord ID="9266" xmlns="http://www.website.com/MyRecord">
    <List>
        <SpecificItem>

Using the following code ...

string xmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(ExportMyRecord));
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, string.Empty);
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, myRecord, xmlnsEmpty);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlizedString = this.UTF8ByteArrayToString(memoryStream.ToArray());

and class structure ...

[Serializable]
[XmlRoot("MyRecord")]
public class ExportMyRecord
{
    [XmlAttribute("ID")]
    public int ID { get; set; }

Now, I've tried various options ...

XmlSerializer xs = new XmlSerializer
                     (typeof(ExportMyRecord),"http://www.website.com/MyRecord");

or ...

[XmlRoot(Namespace = "http://www.website.com/MyRecord", ElementName="MyRecord")]

gives me ...

<?xml version="1.0" encoding="utf-8"?>
<q1:MylRecord ID="9266" xmlns:q1="http://www.website.com/MyRecord">
    <q1:List>
        <q1:SpecificItem>

I need the XML to have the namespace without the prefix as it's going to a third party provider and they reject all other alternatives.

Charles
  • 50,943
  • 13
  • 104
  • 142
OldBob
  • 221
  • 1
  • 2
  • 4

2 Answers2

41

There you go:

ExportMyRecord instance = GetInstanceToSerializeFromSomewhere();
XmlSerializerNamespaces xmlnsEmpty = new XmlSerializerNamespaces();
xmlnsEmpty.Add(string.Empty, "http://www.website.com/MyRecord");
var serializer = new XmlSerializer(
    instance.GetType(), 
    "http://www.website.com/MyRecord"
);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    just wanted to note that you're not using xmlnsEmpty and can be omitted. The overload of serialize that takes XmlSerializerNamespaces doesn't seem to use the string.empty value. – arviman Jan 22 '14 at 07:32
  • Brilliant! was also having issues with ` – Eon Jul 22 '14 at 09:18
  • 4
    xmlnsEmpty is used during serialization: `serializer.Serialize(xmlTextWriter, myRecord, xmlnsEmpty);` – Jamie Ide Apr 22 '15 at 19:06
1

Here's a generic implementation that can be used for any type:

public static void Serialize<T>(T instance, string defaultNamespace, Stream stream)
{
    var namespaces = new XmlSerializerNamespaces();
    namespaces.Add(string.Empty, defaultNamespace);
    var serializer = new XmlSerializer(typeof(T), defaultNamespace);
    serializer.Serialize(stream, instance, namespaces);
}
Sven Vranckx
  • 374
  • 4
  • 5