Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove "d1p1" namespace prefix in DataContractSerializer XML output

I'm using DatacontractSerializer to serialize my domainModel into a xml file. I'm getting output like below.

<z:anyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="1" xmlns:d1p1="DCSerialization_IGITApproach" i:type="d1p1:X" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
  <d1p1:Name z:Id="2">Ankit</d1p1:Name>
  <d1p1:PointsDictionary xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" z:Id="3" z:Size="1">
    <d2p1:KeyValueOfstringPointsArrayq9VX7VJJ>
      <d2p1:Key z:Id="4">key1</d2p1:Key>
      <d2p1:Value xmlns:d4p1="http://schemas.datacontract.org/2004/07/SerializationApproach" z:Id="5">
        <d4p1:points z:Id="6" z:Size="2">
          <d2p1:double>45.5</d2p1:double>
          <d2p1:double>546.45</d2p1:double>
        </d4p1:points>
      </d2p1:Value>
    </d2p1:KeyValueOfstringPointsArrayq9VX7VJJ>
  </d1p1:PointsDictionary>
</z:anyType>

And I want to get rid of these "d1p1" namespace prefixes and just want </PointDictionary> like tag instead of </d1p1:PointsDictionary>. I've tried putting DataMember attribute there on my class properties but it doesn't solve much of the problem. As the output XML file can be edited by the end user so I want a cleaner looking XML file as compared to the above one.

First priority is to control it through code only and if not possible then go for XSLT or any other schema.

like image 536
Bobby Avatar asked Feb 22 '12 09:02

Bobby


2 Answers

Using an empty namespace seems to remove the prefix. Setup your class with the following DataContract attribute:

[DataContract(Namespace="")]
public class MyClass
{ ... }

Then be sure to set the namespace to an empty string when (de)serializing:

DataContractSerializer deserializer = new DataContractSerializer(typeof(MyClass), typeof(MyClass).Name, "");
like image 73
Dru Avatar answered Sep 23 '22 16:09

Dru


It looks like DataContractSerializer doesn't give much control over prefixes. The answer to XML Serialization and namespace prefixes suggests using XmlSerializer if you want to control the namespace prefix.

Your question wasn't clear as to whether you wanted to entirely remove the namespace prefixes for your domain model. Your sample above has several namespace prefixes: d1p1, d2p1, d4p1. Changing namespace for XML file in XSL Translation provides some guidance on prefix renaming using XSLT.

like image 26
Matt Schouten Avatar answered Sep 24 '22 16:09

Matt Schouten