2012-02-17 47 views
14

我試圖輸出,而不XML頭一個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文件outputing。 我不想要字符串技巧。有任何想法嗎?

+1

爲什麼你想要做這樣的事情,我只是好奇:)? – 2012-02-17 17:16:11

+0

因此發現了類似的東西,看看:http://stackoverflow.com/questions/933664/net-xml-serialization-without-xml-root-node。 – 2012-02-17 17:18:35

+1

也許輸出一些片段,這些片段後來被添加到文檔中?或者可能通過像XMPP這樣的套接字發送XML片段呢?大量的使用爲:) – dowhilefor 2012-02-17 17:18:47

回答

20

設置ConformanceLevelFragment,像這樣:

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(); 
+9

謝謝你,但我得到這個錯誤信息:System.InvalidOperationException:WriteStartDocument不能與ConformanceLevel.Fragment創建作家被調用。 – orange 2012-02-17 17:22:43

+8

@orange我有同樣的異常拋出,但設置'OmitXmlDeclaration = true'並明確設置'ConformanceLevel = ConformanceLevel.Auto'給了我預期的結果。 – Grx70 2015-01-20 10:47:04

+0

@ Grx70我有同樣的問題,並且您的修補程序也適用於我,謝謝。 – 2015-02-20 09:49:33

4

看看documentation。 在那裏你看到

The XML declaration is always written if ConformanceLevel is set to Document, even if OmitXmlDeclaration is set to true.

The XML declaration is never written if ConformanceLevel is set to Fragment. You can call WriteProcessingInstruction to explicitly write out an XML declaration.

所以你需要添加

ConformanceLevel = ConformanceLevel.Fragment; 
+0

我用'ConformanceLevel = ConformanceLevel.Fragment'但系列化失敗嘗試。然而'ConformanceLevel = ConformanceLevel.Auto'就像一個魅力(就像它在迭戈的回答書面) – oleksa 2017-10-25 08:32:01

1

如果使用序列化過載(流,對象, XmlSerializerNamespaces)並提供null作爲XmlSerializerNamespaces XmlSerializer不會嘗試失敗的WriteStartDocument。嘗試:

xs.Serialize(xw, obj, null); 
+1

這也適用。如果您是通過實現IXmlSerializable接口自定義串行化對象鏈的一部分,那麼您已經擁有一個XmlWriter,所以此解決方案變得更簡單。 – NthDeveloper 2017-04-03 11:19:53