views:

248

answers:

2

Hi

Using C# and .Net 3.5; I am trying to generate an XML document that contains the default namespace without a prefix using XMLSerializer. eg.

<?xml version="1.0" encoding="utf-8" ?>
<MyRecord ID="9266" xmlns="http://www.website.com/MyRecord"&gt;
    <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"&gt;
    <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. Any suggestions?

No responses so far. Has anyone experienced this or know how to solve it?

+1  A: 

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
A: 

Thanks Darin. It was staring me in the face all the time.