如何使XmlSerializer不能以<! - ?xml? - >开头?

时间:2009-09-09 13:21:59

标签: c# xml xml-serialization ofx

我正在使用的文件格式(OFX)类似XML,在类似XML的位开始之前包含一堆纯文本格式。它不喜欢在纯文本和XML部分之间,所以我想知道是否有办法让XmlSerialiser忽略它。我知道我可以浏览文件并删除该行,但是首先不写它会更简单,更清洁!有什么想法吗?

2 个答案:

答案 0 :(得分:6)

您必须操作调用Serialize方法时使用的XML编写器对象。其Settings属性具有OmitXmlDeclaration属性,您需要将其设置为true。您还需要设置ConformanceLevel属性,否则XmlWriter将忽略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();

答案 1 :(得分:4)

不是太难,您只需序列化为显式声明的XmlWriter,并在序列化之前在该编写器上设置选项。

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