2013-03-01 62 views
0

我在嘗試序列化XML並創建一個文件。我從使用xsd.exe自動從XSD生成的對象序列化。該文件進程並被創建得很好。但每當我運行它針對一種驗證工具,我得到一個錯誤內容不允許在Prolog將XML序列化爲文件導致畸形?

我的猜測是,有XML聲明前,一些畸形的字符,但我好像沒有他們或看到任何字節有可能。這裏是我的代碼序列化和創建XML文檔:

XmlSerializer ser = new XmlSerializer(typeof(ContinuityOfCareRecord)); 
      XmlWriterSettings settings = new XmlWriterSettings() 
      { 
       Encoding = Encoding.UTF8, 
       ConformanceLevel = ConformanceLevel.Document, 
       OmitXmlDeclaration = false, 
       Indent = true, 
       NewLineChars = "\n", 
       CloseOutput = true, 
       NewLineHandling = NewLineHandling.Replace, 
       CheckCharacters = true 
      }; 
using (XmlWriter myWriter = XmlWriter.Create(ms, settings)) 
      { 
       myWriter.Flush(); 
       //myWriter.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"ccr.xsl\""); 
       ser.Serialize(myWriter, myCCR); 
      } 

看起來很簡單,但如果有在輸出XML文件的開頭畸形人物,我怎麼去刪除的人物?

XML文檔開始像這樣:

<?xml version="1.0" encoding="utf-8"?> <ContinuityOfCareRecord xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:astm-org:CCR"> <CCRDocumentObjectID>testccr</CCRDocumentObjectID> <Language>

看起來是正確的,但驗證只是不喜歡它。我一整天都在桌子上敲着頭,所以任何示例代碼都會非常有幫助!

感謝

+0

你碰到什麼驗證工具?你能否將XML反序列化回C#中的一個對象而不出錯? – DiskJunky 2013-03-01 23:39:10

回答

0

看起來像一個BOM字符的問題,以這種方式編寫的代碼可以幫助:

using (XmlTextWriter myWriter = new XmlTextWriter(ms, new System.Text.UTF8Encoding(false))) 
     { 
      myWriter.Flush(); 
      //myWriter.WriteProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"ccr.xsl\""); 
      ser.Serialize(myWriter, myCCR); 
     } 

這將刪除BOM字符,並且該文件將被UTF-8編碼沒有BOM。

+0

我錯過了什麼嗎?我以爲你不能創建一個XMLWriter的實例。我實際上在該行發生錯誤.. – Encryption 2013-03-01 23:49:35