簡體   English   中英

如何在序列化時跳過xml聲明?

[英]How can I skip xml declaration when serializing?

我試圖輸出一個沒有xml頭的xml文件,就像我試過的那樣:

Type t = obj.GetType();
XmlSerializer xs=new XmlSerializer(t);
XmlWriter xw = XmlWriter.Create(@"company.xml",
                                        new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true });
xs.Serialize(xw,obj);
xw.Close();

但它仍然在xml文件中輸出。 我不想要字符串技巧。 有任何想法嗎?

ConformanceLevel設置為Fragment ,如下所示:

Type t = obj.GetType();
XmlSerializer xs=new XmlSerializer(t);
XmlWriter xw = XmlWriter.Create(@"company.xml",
                              new XmlWriterSettings() { 
                                   OmitXmlDeclaration = true
                                   , ConformanceLevel = ConformanceLevel.Auto
                                   , Indent = true });
xs.Serialize(xw,obj);
xw.Close();

看看文檔 你看到了

如果將ConformanceLevel設置為Document,則始終會寫入XML聲明,即使OmitXmlDeclaration設置為true也是如此。

如果ConformanceLevel設置為Fragment,則永遠不會寫入XML聲明。 您可以調用WriteProcessingInstruction來顯式寫出XML聲明。

所以你需要添加

ConformanceLevel = ConformanceLevel.Fragment;

如果使用Serialize重載(Stream,Object,XmlSerializerNamespaces)並將null作為XmlSerializerNamespaces提供,則XmlSerializer將不會嘗試失敗的WriteStartDocument。 嘗試:

xs.Serialize(xw, obj, null);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM