2010-03-23 4 views
16

J'essaie de générer un document XML contenant l'espace de noms par défaut sans préfixe en utilisant XmlSerializer, par ex.Comment ajouter un espace de nom par défaut sans préfixe à l'aide de XMLSerializer

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

En utilisant le code suivant ...

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()); 

et la structure de classe ...

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

Maintenant, je l'ai essayé différentes options ...

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

ou ...

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

me donne ...

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

J'ai besoin XML d'avoir l'espace de noms sans le préfixe comme il va à un fournisseur tiers et ils rejettent toutes les autres alternatives.

Répondre

29

Là vous allez:

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" 
); 
+0

solution parfaite! – viperguynaz

+0

Je voulais juste noter que vous n'utilisez pas xmlnsEmpty et peut être omis. La surcharge de serialize qui prend XmlSerializerNamespaces ne semble pas utiliser la valeur string.empty. – arviman

+0

Brillant! avait aussi des problèmes avec ' Eon

Questions connexes