2011-03-24 11 views
16

Al utilizar la configuración predeterminada con el XmlSerializer, generará el XML como un valor formateado.Evitar que XmlSerializer dé formato a la salida

IE: algo en esta línea.

<?xml version="1.0" encoding="utf-8"?> 
<ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Stock> 
    <ProductCode>12345</ProductCode> 
    <ProductPrice>10.32</ProductPrice> 
    </Stock> 
    <Stock> 
    <ProductCode>45632</ProductCode> 
    <ProductPrice>5.43</ProductPrice> 
    </Stock> 
</ArrayOfStock> 

¿Cómo se puede evitar cualquier tipo de formateo en la salida? Entonces, lo que estoy buscando lograr es esto.

<?xml version="1.0" encoding="utf-8"?> 
<ArrayOfStock xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Stock> 
     <ProductCode>123456</ProductCode> 
     <ProductPrice>10.57</ProductPrice> 
    </Stock> 
    <Stock> 
     <ProductCode>789123</ProductCode> 
     <ProductPrice>133.22</ProductPrice> 
    </Stock> 
</ArrayOfStock> 

EDIT: El código completo de mi método es

public static String Serialize(Stock stock) 
{ 
    XmlSerializer serializer = new XmlSerializer(typeof(Stock)); 

    using (StringWriter stringWriter = new StringWriter()) 
    { 
     serializer.Serialize(stringWriter, stock); 
     return stringWriter.ToString(); 
    }    
} 
+0

¿Por qué es importante el formato? ¿Está causando un problema? –

Respuesta

22

Has probado esto:

var serializer = new XmlSerializer(typeof(MyClass)); 

using (var writer = new StreamWriter("file.path")) 
using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { Indent = false })) 
{ 
    serializer.Serialize(xmlWriter, myObject); 
} 

Hay algunas opciones más en XmlWriterSettings que es posible que desee explorar.

+0

Saludos, trabajó un encanto! –

+2

Creo que la sangría es por defecto falso porque tenía el mismo código que el tuyo (sin Configuración) y quería formatearlo, así que tuve que cambiar la sangría a verdadero. – sluki

+0

Sí, la sangría es falsa por defecto en 'XmlWritterSettings' así que supongo que se puede omitir en el código anterior. Pero si usa el 'XmlSerializer' sin darle explícitamente un' XmlWriter', usará el suyo propio y habilitará el formateo/indentación de forma predeterminada. –

0

..

XmlSerializer xmlser = new XmlSerializer(...); 

XmlWriterSettings settings = new XmlWriterSettings {Indent = false}; 

using (XmlWriter xw = XmlWriter.Create(stream, settings)) 
{ 

...

0

Es simple analizar el XML resultante y eliminar y las nuevas líneas y pestañas ...
usando 'Indent = false', todavía pondrá elementos en las líneas nuevas no?

+0

Ok, parece que la opción Sangría controla algo más que la sangría ... mal nombrado tal vez? –

Cuestiones relacionadas