Add prefixes and namesapce to xml serialization

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Im working in a Mexican tax calculation program and the government provided the following XSD file http://www.sat.gob.mx/cfd/3/cfdv32.xsd, with xsd.exe help I have converted it to a C# class which is quite big so Ill just provide a link to it in order
to no bloat this post with code: http://pastebin.com/r3VCgFMU.<br/>
<br/>
After filling SOME of the class fields (So the example doesnt get too big) I tried to serialize the XML as follows:<br/>
<pre class="prettyprint XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNameSpace.Add("schemaLocation", "http://www.sat.gob.mx/cfd/3/cfdv32.xsd");
xmlNameSpace.Add("cfdi", "www.sat.gob.mx/cfd/3"); XmlTextWriter xmlTextWriter = new
XmlTextWriter("c:\temp\pruebas.xml", Encoding.UTF8);
xmlTextWriter.Formatting = Formatting.Indented;
XmlSerializer xs = new XmlSerializer(typeof(Comprobante));
xs.Serialize(xmlTextWriter, comprobante, xmlNameSpace);
xmlTextWriter.Close();[/code]
Which gives me this output:<br/>
<br/>
<pre class="prettyprint <?xml version="1.0" encoding="utf-8"?>
<Comprobante xmlns:cfdi="www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:schemaLocation="http://www.sat.gob.mx/cfd/3/cfdv32.xsd" version="3.2" fecha="0001-01-01T00:00:00" subTotal="0" total="0" tipoDeComprobante="ingreso" xmlns="http://www.sat.gob.mx/cfd/3
<Emisor rfc="DERH9145202V4
<DomicilioFiscal calle="Calle1" colonia="Colonia" municipio="municipio" estado="estado" pais="pais" codigoPostal="07000" />
<RegimenFiscal Regimen="Peque" />
</Emisor>
</Comprobante>[/code]
As we can see in an example provided by the government ( ftp://ftp2.sat.gob.mx/asistencia_servicio_ftp/publicaciones/solcedi/ejemplo1%20cfdv3.xml ) my generated file lacks some points:<br/>
<pre class="prettyprint * <Comprobante... should be <cfdi:Comprobante
* <Emisor.. should be <cfdi:Emisor
* and so on and so forth with all elements...
* xmlns:schemaLocation should be xsi:schemaLocation
* Im getting and additional xmlns="http://www.sat.gob.mx/cfd/3" at the end of the Comprobante declaration[/code]
How can I achieve this changes in my xml? :D

View the full article
 
Back
Top