¿Cómo hago XmlSerialiser se inicia con Xml?>?
-
22-09-2019 - |
Pregunta
El formato de archivo que estoy trabajando (OFX) es similar a XML y contiene un montón de cosas en texto plano antes de que el XML como poco comienza. Que no le gusta tener entre el texto plano y partes XML embargo, por lo que estoy preguntando si hay una manera de conseguir XmlSerialiser hacer caso omiso de eso. Sé que podría pasar por el archivo y acabar con esa línea, pero sería más simple y más limpio que lo escriba en el primer lugar! Algunas ideas?
Solución
No es demasiado difícil, sólo hay que serializar a un XmlWriter declarado de forma explícita y defina las opciones de que el escritor antes de serializar.
public static string SerializeExplicit(SomeObject obj)
{
XmlWriterSettings settings;
settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlSerializerNamespaces ns;
ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer serializer;
serializer = new XmlSerializer(typeof(SomeObject));
//Or, you can pass a stream in to this function and serialize to it.
// or a file, or whatever - this just returns the string for demo purposes.
StringBuilder sb = new StringBuilder();
using(var xwriter = XmlWriter.Create(sb, settings))
{
serializer.Serialize(xwriter, obj, ns);
return sb.ToString();
}
}
Otros consejos
Vas a tener que manipular el objeto escritor XML se utiliza al llamar a la Serialize
método. Su propiedad Settings
tiene una OmitXmlDeclaration
propiedad, que querrá establecido en true. También tendrá que establecer la propiedad ConformanceLevel
, de lo contrario el XmlWriter ignorará la propiedad OmitXmlDeclaration
.
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlWriter writer = XmlWriter.Create(/*whatever stream you need*/,settings);
serializer.Serialize(writer,objectToSerialize);
writer.close();